The 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 displayed data. But when I use fread, it displays all the content. By the way, this is a cgi script to load the html file using the post method. Any help would be greatly appreciated.

+4
source share
2 answers

Both functions can be well documented ( fread , fgets ) on the C ++ website. Refer to them for depth and technical difference.

In short, fgets will read until the first new line, the maximum bytes to read immediately or EOF that are ever sent first, while fread will read a certain number of words (where I define a word as a piece of bytes, say, a group of 4 bytes) and stop when this limit is reached or 0 bytes are read (usually this means EOF or error).

If you want to use any function to read before EOF , then it will look like this:

 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). } 
+10
source

fgets stops reading when meeting \n , and fread reads.

+2
source

Source: https://habr.com/ru/post/1497238/


All Articles