[英]Using fgets() with pipe
I need to write program, which work on Linux OS: 我需要编写在Linux OS上可以运行的程序:
when the main program starts, a child program separates from main program and child can be executed when it gets an interruption from parent program; 当主程序启动时,子程序与主程序分离,当子程序被父程序中断时,子程序可以执行。
parent program waits for a text line, enetered from keyboard (text line should end by pressing ); 父程序等待从键盘输入的文本行(文本行应按来结束);
after the text line is entered, parent program sends an interruption to child program, which reads the text line trough "Pipe" channel and creates a text file with it. 输入文本行后,父程序将中断发送给子程序,子程序将通过“管道”通道读取文本行并使用该文本行创建文本文件。
if an empty line is entered, then both parts of the program end their work. 如果输入空行,则程序的两个部分都将结束工作。
The problem is, I know that it is bad to use gets(), so how can I use fgets() instead in my case? 问题是,我知道使用gets()很不好,那么在我的情况下如何使用fgets()呢?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
FILE *f;
int main(void)
{
int pfds[2];
char buf[1000];
pipe(pfds);
f = fopen("input.txt", "w");
fclose(f);
do
{
if (!fork())
{
printf("PARENT: enter input text from keyboard\n");
gets(buf);
printf("PARENT: writing to the pipe\n");
write(pfds[1], buf, 1000);
printf("PARENT: exiting\n");
exit(0);
}
else
{
f = fopen("input.txt", "a+");
printf("CHILD: waiting from PARENT\n");
read(pfds[0], buf, 1000);
printf("CHILD: read \"%s\"\n", buf);
fprintf(f,"%s\n", buf);
fclose(f);
printf("CHILD: input.txt file created\n", buf);
wait(NULL);
}
}
while (buf[0] != '\0');
printf("PROGRAM: done\n");
return 0;
}
You have opened file in "w" mode. 您已以“ w”模式打开文件。
f = fopen("program.txt", "w");
w mode creates an empty file for writing. w模式会创建一个用于写入的空文件。 If a file with the same name already exists, its content is erased and the file is considered as a new empty file. 如果已经存在同名文件,则其内容将被删除,并且该文件将被视为新的空文件。
Open the file in "w+" or "a+" mode. 以“ w +”或“ a +”模式打开文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.