简体   繁体   中英

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. But when I use fread , it displays all the content. By the way, this is the CGI script for an html file upload using post method. Any help would be greatly appreciated.

Both functions can be found well documented ( fread , fgets ) on the C++ website. 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).

If you wanted to use either function to read until EOF then it would look as follows:

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读取。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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