c - fread 不读取多行

标签 c file-read

我正在尝试从行中包含一些数字的 .txt 文件中读取数据。

看起来像那样。

例子.txt

123
456
789
555

我将它作为一个二进制文件打开以供阅读,我想逐行读取这个文件,所以我知道每行有 4 个字符(3 个数字和 1 个换行符 '\n')。

我正在这样做:
FILE * fp;

int page_size=4;
size_t read=0;
char * buffer = (char *)malloc((page_size+1)*sizeof(char));
fp = fopen("example.txt", "rb"); //open the file for binary input

//loop through the file reading a page at a time
do {
    read = fread(buffer,sizeof(char),page_size, fp); //issue the read call

    if(feof(fp)!=0) 
      read=0;

    if (read > 0) //if return value is > 0
    {   
        if (read < page_size) //if fewer bytes than requested were returned...
        {
            //fill the remainder of the buffer with zeroes
            memset(buffer + read, 0, page_size - read);
        }

        buffer[page_size]='\0';
        printf("|%s|\n",buffer);
    }

}
while(read == page_size); //end when a read returned fewer items

fclose(fp); //close the file

在 printf 中预期这个结果然后
|123
|
|456
|
|789
|
|555
|

但我采取的实际结果是:
|123
|
456|
|
78|
|9
6|
|66
|

所以看起来在第一个 2 fread 之后它只读取了 2 个数字,并且换行符完全出错了。

那么这里的 fread 有什么问题呢?

最佳答案

您可以使用以下内容逐行读取文件。

   FILE * fp;
   char * line = NULL;
   size_t len = 0;
   ssize_t read;

   while ((read = getline(&line, &len, fp)) != -1) {
       printf("Line length: %zd :\n", read);
       printf("Line text: %s", line);
   }

关于c - fread 不读取多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15428534/

相关文章:

c - 将百分比值分配给一系列值

c - 缓冲区指针作为 c 函数中的参数

python - 使用 C 扩展扩展 python

Python;我们如何复制txt文件中的随机行并删除同一行?

python - python是否有一个文件打开模式结合了 "w+"和 "r"的功能?

objective-c - C 和 Objective C 之间的主要区别是什么。C 中可以进行抽象吗?

c - C 中的链表太慢

c - 将二进制文件加载到未知的结构类型

java - 从两个文件中读取,然后将它们组合并写入第三个文件,java

c - 读取文件直到 C 中的一个字符