Why is the fgets function deprecated?

后端 未结 2 1962
予麋鹿
予麋鹿 2020-11-29 05:47

From The GNU C Programming Tutorial:

The fgets (\"file get string\") function is similar to the gets function. This function is dep

相关标签:
2条回答
  • 2020-11-29 06:01

    No, fgets is not actually deprecated in C99 or the current standard, C11. But the author of that tutorial is right that fgets will not stop when it encounters a NUL, and has no mechanism for reporting its reading of such a character.

    The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file.

    (§7.21.7.2)

    GNU's getdelim and getline have been standardized in POSIX 2008, so if you're targeting a POSIX platform, then it might not be a bad idea to use those instead.

    EDIT I thought there was absolutely no safe way to use fgets in the face of NUL characters, but R.. (see comments) pointed out there is:

    char buf[256];
    
    memset(buf, '\n', sizeof(buf));  // fgets will never write a newline
    fgets(buf, sizeof(buf), fp);
    

    Now look for the last non-\n character in buf. I wouldn't actually recommend this kludge, though.

    0 讨论(0)
  • 2020-11-29 06:23

    This is just GNU propaganda. In no official sense is fgets deprecated. gets however is dangerous and deprecated.

    0 讨论(0)
提交回复
热议问题