Function fread not terminating string by \0

前端 未结 3 2088
遥遥无期
遥遥无期 2020-12-17 20:55

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];         


        
3条回答
  •  独厮守ぢ
    2020-12-17 21:15

    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!

提交回复
热议问题