Does fgets() always terminate the char buffer with \0?

前端 未结 5 1936
忘了有多久
忘了有多久 2021-02-01 21:02

Does fgets() always terminate the char buffer with \\0 even if EOF is already reached? It looks like it does (it certainly does in the implementation presented in the ANSI K&

5条回答
  •  眼角桃花
    2021-02-01 21:56

    If you did open the file in binary mode "rb", and if you want to read Text line by line by using fgets you can use the following code to protect your software of loosing text, if by a mistake the text contained a '\0' byte. But finally like the others mentioned, normally you should not use fgets if the stream contains '\0'.


    size_t filepos=ftell(stream);
    fgets(buffer, buffersize, stream);
    len=strlen(buffer);
    /* now check for > len+1 since no problem if the 
       last byte is 0 */
    if(ftell(stream)-filepos > len+1) 
    {
        if(!len) filepos++;
        if(!fseek(stream, filepos, SEEK_SET) && len)
        {
            fread(buffer, 1, len, stream);
            buffer[len]='\0';
        }
    }
    

提交回复
热议问题