c - 正在创建文件,但未将数据推送到文件中

标签 c

我写了这个 C 程序,它将系统调用作为输入,如 ps -f 或 ls/tmp 等,系统调用的输出被推送到文件,然后从文件中推送它读取并显示输出。

此处正在创建输出文件 /tmp/j 但其中没有数据。有人可以帮我解决这个问题吗?在此先感谢。

我的程序。

#include<stdio.h>
#include<sys/syscall.h>
#include <stdlib.h>

main()
{
    enum msgtype {PROCESS_LIST_REQUEST=1, PROCESS_LIST_RESPONSE, DIRECTORY_LIST_REQUEST, DIRECTORY_LIST_RESPONSE, ERROR_REQUEST};
    struct head{
        int version;
        int msg_length;
        int header_length;
        enum msgtype msg_type;
        char data;
        char *reqtype;
    };

    struct head *buf;
    char buff[10];

    buf = malloc((sizeof(struct head)));
    buf->reqtype=malloc(40);

    char req[10];
    printf("type ps -f on the console \n");
    fgets(req, sizeof(req),stdin);
    buf->reqtype = req;
    printf("%s" , buf->reqtype);
    snprintf(buff, sizeof(buff), "%s>/tmp/j", buf->reqtype);
    printf("%s \n",buff);
    system(buff);
    {
        FILE *fp;
        char c;
        fp = fopen("/tmp/j", "r");
        if (fp == NULL)
            printf("File doesn't exist\n"); 
        else
        {
            do {
                c = getc(fp); /* get one character from the file*/
                putchar(c); /* display it on the monitor*/
            } while (c != EOF); /* repeat until EOF (end of file)  */
        }
        fclose(fp);
    }
}

最佳答案

您的代码中有几个错误。

1) 为你的 buff 分配一些大于 10 的内存。 10 是不够的。你的字符串超过了 10 的大小。我在我的机器上把它设为 20 并检查了。

2) fgets(req, sizeof(req),stdin); 正在读取字符串末尾的 \n。删除最后一个字符。 req[strlen(req) - 1] = '\0';

参见 this fgets 的手册页

关于c - 正在创建文件,但未将数据推送到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33383751/

相关文章:

c - 管道中的其他程序

c - 是否可以使用两种编码语言(python 和 C 语言)来制作一个程序?

C:查找字符串中的特定字符

arrays - 将数组分配给结构中的数组

c - "typedef char A[max_size]"是什么意思?

c - Linux-C 从损坏的共享内存中读取数据

c++ - 将 int 转换为 ASCII 字符

c - mktime 和 timelocal 的区别

c - 给定范围内的素数

c - 为什么 scanf 在 freopen 函数中跳过 '\n' ?