C语言中的read()和fgets()之间的区别 [英] Difference between read() and fgets() in C

查看:359
本文介绍了C语言中的read()和fgets()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从stdin流中读取.使用read()或fgets()从stdin流中读取有什么区别.

I want to read from a stdin stream. Is there any difference in using read() or fgets() to read from the stdin stream.

我将以下两段代码与fgets附加在一起并阅读. 使用fgets,我可以使用Java程序轻松地从c程序中读写. 通过读写,我的java程序挂起,等待C程序的输出未出现.

I am attaching the following two pieces of code with fgets and read. With fgets I can use a java program to write and read from the c program easily. With read and write my java program hangs waiting for the output from C program which does not come.

我正在阅读一行,将其保留在buf中,并在其后附加A.

I am just reading a line keeping it in buf and appending A to it.

Java程序可以与下面的与fgets和puts一起使用的程序进行对话.

Java program is able to talk to the following program which works with fgets and puts.

#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()

but not with read() and 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));

    }
}

}

有人可以说出原因.我仍然很难弄清

Could some one tell the reason. I am still finding it hard to figure out

推荐答案

  • fgets是一个函数,read是一个系统调用
  • fgets是标准C,read不是
  • fgets是stdio缓冲的,read不是
  • fgets适用于FILE *read适用于文件描述符
  • fgets读取直到换行,read读取告诉您的内容
    • fgets is a function, read is a system call
    • fgets is standard C, read is not
    • fgets is stdio buffered, read is not
    • fgets works with a FILE *, read works with a file descriptor
    • fgets reads until newline, read reads how much you tell it to
    • 需要更多吗?

      这篇关于C语言中的read()和fgets()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆