C - fgets() - 如果字符串更长怎么办?

标签 c string file char gets

假设我有一个包含长度为 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/

相关文章:

c - 使 C 源代码中的大常量更具可读性?

C++ 字符串使用分配的最大缓冲区?

java - 如何根据多个分隔符 split() 字符串?

c - 如何读取存储在二进制文件中的数组或变量,并在程序中打印出来?

c - 将 int 传递给需要 char* 的函数

c - Malloc 语句给出段错误 11

C 使用 For 语句显示素数

c++ - 比较字符串的瓶颈

python将文件复制到Windows上的网络位置而不映射驱动器

swift - Apple Swift 3.0 数据