我写了这个 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/