假设我有一个包含长度为 10 的字符串的文件:
abcdefghij
然后使用大小为 4 的缓冲区使用 fgets()
逐行读取我的文本文件。
我将不得不在循环中调用 fgets()
以确保读取整行。
但是,在第一次调用时,它会读取前 3 个字符 (buffer size -1)
对吧?即使未到达字符串的实际结尾,它还会在我的 4 字符缓冲区的最后位置附加一个空终止字符,还是会用 4 个字符填充它并且在我的缓冲区末尾没有空终止字符?这将使对 strlen()
的调用变得不可能?
谢谢你:)
最佳答案
它在文档中。
逐字记录来自 man fgets
(我用斜体字):
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
HP-UX 11 手册页的逐字记录(我用斜体字):
fgets()
Reads characters from the stream into the array pointed to by s, until n-1 characters are read, a new-line character is read and transferred to s, or an end-of- file condition is encountered. The string is then terminated with a null character.
来自POSIX specs :
The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.
最后一点 from MSDN :
The fgets function reads a string from the input stream argument and stores it in str. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in str is appended with a null character. The newline character, if read, is included in the string.
关于C - fgets() - 如果字符串更长怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20516824/