Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c中使用缓冲区读取文件_C_File_Io - Fatal编程技术网

在c中使用缓冲区读取文件

在c中使用缓冲区读取文件,c,file,io,C,File,Io,这是我的代码,其中fp是打开的文件 unsigned char string[10]; while(fgets(string, 10, fp)) // do stuff with string 现在我想循环数组中的每个字符,但是当文件只有5个字符时,数组是如何填充的。它是否包含EOF字符或其他内容?来自: fgets()从流中最多读取一个小于大小的字符 并将它们存储到s指向的缓冲区中。阅读结束后停止 EOF或换行符。如果读取换行符,它将存储到 缓冲器终止的空字节('\0')存储在最后一

这是我的代码,其中fp是打开的文件

unsigned char string[10];
while(fgets(string, 10, fp))
    // do stuff with string
现在我想循环数组中的每个字符,但是当文件只有5个字符时,数组是如何填充的。它是否包含EOF字符或其他内容?

来自:

fgets()从流中最多读取一个小于大小的字符 并将它们存储到s指向的缓冲区中。阅读结束后停止 EOF或换行符。如果读取换行符,它将存储到 缓冲器终止的空字节('\0')存储在最后一个字节之后 缓冲区中的字符

这意味着如果您的文件在一行中只包含5个字符(即假设不超过一个换行符), 然后,
string
将包含5个字符,
string
中的第6个字节将是终止的空字节

要在其上循环,可以使用:

for(i = 0; string[i]; i++) { //until the terminating byte
    char ch = string[i];
    ...
}

字符串存储在数组中,长度为0,以\0结尾 所以您可以在循环或访问每个字符串时使用\0

   char string[100] //
    for(i=0;string[i]!=\0;i++) // looping until I becomes \0
        {
        ch=string[i];
        }

EOF
不是字符。这实际上就是它背后的想法。fgets将获得指定数量的字符,或者直到找到EOF或换行符。资料来源: