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

Dani AI

Generated

and are spot on: use fgets for line-oriented, human-readable text and fread for fixed-size or binary blocks. Two practical gotchas: (1) fgets will include the trailing '\n' if it fits and always writes a terminating '\0' — it returns NULL only if an error occurs or EOF is reached before any characters are read (if some characters are read before EOF it still returns the buffer). (2) fread does not inspect content (no delimiter, no automatic '\0') and its return value is the number of items read, so always check ferror/feof when the count is short. See the C reference pages for details: fgets and fread.

#include <string.h>

char line[256];
if (fgets(line, sizeof line, fp)) {
    line[strcspn(line, "\n")] = '\0';
}
size_t n = fread(buf, 1, want, fp);
if (n < want) {
    if (ferror(fp)) { /* handle error */ }
    else if (feof(fp))  { /* reached EOF */ }
}

If you need a C string from fread, read at most cap-1 and append '\0'. On Windows open binary files with "rb"/"wb" to avoid CR/LF translation. Finally, 's fgetc loop is fine for simple printing, but for parsing lines use fgets (or POSIX getline for variable-length lines) and for bulk/binary I/O prefer fread.

Recommended Answers

All 3 Replies

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:

  1. fgets terminates the string with '\0', but fread does not
  2. fgets uses '\n' as a delimiter as well as an upper limit, but fread only uses an upper limit

"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"


#include<stdio.h>
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);
}

commented: Congratulations, you've ressurected a more than one year old thread + posted some rubbish without code tags! -1
commented: For bumping old threads! Man, are people just getting more stupid? +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.