gpt4 book ai didi

c - fread 不读取多行

转载 作者:行者123 更新时间:2023-12-02 00:10:59 26 4
gpt4 key购买 nike

我正在尝试从行中包含一些数字的 .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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com