我想从标准输入流中读取数据。使用 read() 或 fgets() 从 stdin 流读取有什么区别吗?
我用 fgets 附加了以下两段代码并阅读。
有了fgets,我可以使用java程序轻松地编写和读取c程序。
通过读写,我的 java 程序挂起,等待 C 程序的输出,但 C 程序没有输出。
我只是读一行将其保存在 buf 中并在其中附加 A 。
Java 程序能够与以下使用 fget 和 put 的程序进行对话。
#include <stdio.h>
#include <string.h>
#define SIZE 200000
main()
{
int rc;
int df;
int i;
char buf[SIZE];
for(i=0;i<=120000;i++) {
memset(buf,'\0',SIZE);
if(!fgets(buf,SIZE-1,stdin))
continue;
strcat(buf,"A_A_A_A_A_A_A");
puts(buf);
}
}
但不能使用 read() 和 write()
main()
{
int rc;
int df;
int i;
char buf[32768];
rc = fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
//rc = fcntl(fileno(stdout), F_SETFL, O_NONBLOCK);
FILE *fp;
for (;;)
{
int rc=-1;
memset(buf,'\0',32768);
//rc = fread(buf,5, 1, stdin);
rc = read(fileno(stdin),buf,32768);
if (rc > 0)
{
strcat(buf,"B_B_B_B_B_B_B_B_B");
write(fileno(stdout),buf,strlen(buf));
}
}
}
有哪位能说说原因吗。我还是觉得很难弄清楚