4

我正在尝试从行中有一些数字的 .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 有什么问题呢?

4

2 回答 2

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);
   }
于 2013-03-15T09:34:29.907 回答
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);

您可以尝试使用此代码,此代码运行良好。

我尝试了您的代码,并且在我的系统上也运行良好。

于 2013-03-15T09:53:04.000 回答