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