简体   繁体   English

fgets 和 fread 的区别

[英]Difference between fgets and fread

I have the following code below:我有以下代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    int lendata;
    printf("Content-type:text/html\n\n");
    printf("<html><body>");

    lendata = atoi(getenv("CONTENT_LENGTH"));
    char *buf = malloc(lendata+1);
    fread(buf,lendata,1,stdin);

    printf("%s\n<br>",buf); 
    printf("%d",lendata);   

    free(buf);

    printf("</body></html>");
    return 0;
}

When I use fgets , it truncates the data displayed.当我使用fgets ,它会截断显示的数据。 But when I use fread , it displays all the content.但是当我使用fread ,它会显示所有内容。 By the way, this is the CGI script for an html file upload using post method.顺便说一下,这是使用 post 方法上传 html 文件的 CGI 脚本。 Any help would be greatly appreciated.任何帮助将不胜感激。

Both functions can be found well documented ( fread , fgets ) on the C++ website.可以在 C++ 网站上找到这两个函数的详细文档( freadfgets )。 Refer to them for the in depth and technical difference.请参阅它们以了解深度和技术差异。

In short, fgets will read until the first new line, maximum bytes to read at once, or EOF , which ever is sent first whereas fread will read a specific number of words (where I define a word as a chunk of bytes, say groups of 4 bytes) and stop when that limit has been reached or 0 bytes have been read (typically means EOF or error).简而言之, fgets将读取到第一个新行,一次读取的最大字节数或EOF ,以先发送者EOF ,而fread将读取特定数量的单词(我将单词定义为一个字节块,例如组4 个字节)并在达到该限制或读取 0 个字节时停止(通常表示EOF或错误)。

If you wanted to use either function to read until EOF then it would look as follows:如果您想使用任一函数读取直到EOF则它如下所示:

char buffer[ buff_len ];

// ... zero-fill buffer here.

while ( fgets( buffer, buff_len, stdin ) != EOF ) {
  // ... do something with buffer (will be NULL terminated).
}

while ( fread( buffer, sizeof( buffer[ 0 ] ), sizeof( buffer ) / sizeof( buffer[ 0 ] ), stdin ) != 0 ) {
  // ... do something with buffer (not necessarily NULL terminated).
}

fgets在遇到\\n时停止读取,而fread读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM