954,170 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Diff between fread() and fgets()

what is the difference between fread() and fgets()?

nagaa
Newbie Poster
7 posts since May 2008
Reputation Points: 10
Solved Threads: 0
 

fgets reads a single line of characters, but fread reads a block of unidentified objects. fgets uses '\n' as a delimiter, but fread doesn't inspect any of the objects so it relies on a limit of the number of objects. If you're using fread to read string data, the only two significant differences are:fgets terminates the string with '\0', but fread does not
fgets uses '\n' as a delimiter as well as an upper limit, but fread only uses an upper limit

Radical Edward
Posting Pro
545 posts since May 2008
Reputation Points: 361
Solved Threads: 97
 

"fgets" is essentially a simplified version of "fread".

"fgets" is good for (and should only be used for) reading character strings from an input stream, be it a file or the stdin device.

"fread" is suited for any data type, such as binary (hex) data. it gives you more rope to hang yourself with, so if you're just wanting to read ascii text, stick with "fgets"

http://www.cplusplus.com/reference/clibrary/cstdio/fread.html
http://www.cplusplus.com/reference/clibrary/cstdio/fgets.html

jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
 

#include
main()
{
FILE *fp1;
char c;
//c=fgetc(fp1);

fp1=fopen("readdata.c","r");
if(fp1==NULL)
{
printf("\n Can't open file for reading");
//exit(1);
}
printf("\n The contents of the file is \n");
while((c = fgetc(fp1)) != EOF)
{
printf("%c",c);
}
fclose(fp1);
}

molu mammen
Newbie Poster
1 post since Oct 2009
Reputation Points: 9
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You