Difference between fgets and fread
c, cgi, post
Solution
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).
}
Problem
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.