Function fread not terminating string by \0

心不动则不痛 提交于 2019-11-28 00:13:50

问题


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?


回答1:


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.




回答2:


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.




回答3:


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!



来源:https://stackoverflow.com/questions/8869352/function-fread-not-terminating-string-by-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!