c++ 文件读操作 位置指针问题

2025-03-10 17:47:54
推荐回答(2个)
回答1:

换行的地方有个回车符和换行符,各占一个字节了,

#include "stdafx.h"
#include 
#include 
#include 
#define PAUSE int pause;\
 scanf("%d",&pause);
int _tmain(int argc, _TCHAR* argv[])
{
 FILE *pFile;
 pFile=fopen("me.txt","r");
 char a[5],b[5],c[5];
 memset(a,0,5);
 memset(b,0,5);
 memset(c,0,5);
 fread(a,1,4,pFile);
 printf("%s\n",a);
 int pos;
 pos=ftell(pFile);
 printf("pos=%d\n",pos);
 fread(b,1,4,pFile);
//文件指针从当前位置前进2个字节,因为有个\n\t     
 fseek(pFile,2,SEEK_CUR); 
 printf("%s\n",b);
 pos=ftell(pFile);
 printf("pos=%d\n",pos);
 fread(c,1,4,pFile);
 printf("%s\n",c);
 pos=ftell(pFile);
 printf("pos=%d\n",pos);
 fclose(pFile);
 PAUSE;
 return 0;
}

 

回答2:

你的程序是没问题的。

结果和你预期不一致主要是字符编码的问题,你打开文件的时候是以字符模式打开的,所以从文件中读取数据的时候会做一些转换(比如在Windows平台下换行包含两个字符\r\n,所以占用两个字节),这就是读取二进制信息的时候要加上std::ios::binary标识的原因。

改成“ ifstream f1("d:\\me.txt",ios::in | ios::binary ); ” 试试。