The fread function does not end the line \ 0

New in C files trying to read a file via fread

Here is the contents of the file:

line1 how 

Used code:

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

When var 'c' is output, the contents appear with a random character at the end (for example: line1 *)

Is fread not breaking the line or am I missing something?

+7
source share
3 answers

Not. The fread function simply reads a few elements, it does not have the concept of a "string".

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

Personally, I would go with fgets .

+10
source

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

If you want to be safe, initialize all bytes in your array c equal to zero (via bzero or something like that) and when you start reading, you will have a terminating zero.

I linked the two pages of the manual for fread and bzero , and I hope this helps you.

+2
source

Too bad I'm a little late to the party.

No, this is not for you. This must be done manually. Fortunately, it is not difficult. I like to use fread () return to set NUL as follows:

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

and now you have a line with a completed \ 0, and as a bonus we have a great variable x, which actually saves us from the trouble of running strlen () if we ever need it later. orderly!

+1
source

All Articles