Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function fread not terminating string by \0

Tags:

c

fread

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?

like image 998
Akash Avatar asked Jan 15 '12 11:01

Akash


1 Answers

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.

like image 184
cnicutar Avatar answered Nov 15 '22 23:11

cnicutar