fread不会读取多行

时间:2013-03-15 09:16:46

标签: c file-read

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

看起来像那样。

example.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
|

所以看起来在前两个fread之后它只读取了2个数字,并且新行符号出现了一些问题。

所以fread在这里出了什么问题?

2 个答案:

答案 0 :(得分:2)

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

   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);
   }

答案 1 :(得分:1)

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 (read > 0) //if return value is > 0
{
    buffer[page_size]='\0';
    printf("|%s|\n",buffer);
}

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

fclose(fp);

您可以尝试使用此代码,此代码运行正常。

我尝试使用您的代码,并且在我的系统上运行正常。