15

New to files in C, trying to read a file via fread

Here's the content of the file:

line1 how

Code used:

char c[6];
fread(c,1,5,f1)

When outputting var 'c', the contents appear with a random character at the end (eg: line1*)

Does fread not terminate the string or am I missing something?

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
Akash
  • 4,956
  • 11
  • 42
  • 70

3 Answers3

16

No. The fread function simply reads a number of elements, it has no notion of "strings".

  • You can add the NUL terminator yourself
  • You can use fgets / fscanf instead

Personally I would go with fgets.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • for those interested, an example implementation to remove newline from fgets is given here: http://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input – m-ric Oct 19 '12 at 17:57
4

Sorry i'm a little late to the party.

No, fread doesn't handle this for you. It must be done manually. Luckily its not hard. I like to use fread()'s return to set the NUL like so:

char buffer[16+1]; /*leaving room for '\0' */
x = fread(buffer, sizeof(char), 16, stream);
buffer[x]='\0';

and now you have yourself a \0 terminated string, and as a bonus, we have a nifty variable x, which actually saves us the trouble of running strlen() if we ever needed it later. neat!

deadPix3l
  • 41
  • 2
1

The man page for fread says nothing about adding a terminating zero at the end of the file.

If you want to be safe, initialize all the bytes in your c array to be zero (via bzero or something like that) and when you read in, you'll then have a terminating null.

I've linked the two man pages for fread and bzero and I hope that helps you out.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • [`bzero()`](http://man7.org/linux/man-pages/man3/bzero.3.html) is deprecated (and has been removed from POSIX.1-2008) in favour of [`memset()`](http://man7.org/linux/man-pages/man3/memset.3p.html). – alx - recommends codidact Jan 05 '20 at 01:04