C++文件操作的一个疑惑
我是要用C++写一个要将命名为“in.txt”文件中读取信息(暂不考虑中文和回车的处理),颠倒输出在另个文件中。
很简单,但是我测试的时候发现一个奇怪的现象:
使用ios::cur去寻址比用ios::beg寻址要慢一点。我是使用一个1000000字节的文本文件测试(测试数据生成代码在最后面),测试结果如下: 
前三个是使用ios::beg寻址的,后三个是使用ios::cur寻址的。很明显前者要快一点。这一点,我很是疑惑。为什么从当前位置开始寻址要比从起始位置寻址要慢,没天理啊。。。
说一下环境
系统:windows xp professional.
编译器:VC++6.0
附代码:
#include<iostream>
#include<fstream>
#include<ctime>
int main()
{
clock_t start,finish;
start=clock();
long len=-1L;
std::ifstream inp("in.txt",std::ios::in);
std::ofstream oup("out.txt",std::ios::out);
inp.seekg(len,inp.end);
len=(long)inp.tellg();
std::cerr<<"A total of "<<len+1<<" bytes\nOpening file ...";
while(len>=0)
{
/******使用ios::cur寻址的代码********/
oup<<(char)inp.get();
inp.seekg(-2L,inp.cur);
len--;
/*******使用ios::beg寻址的代码********
inp.seekg(len--,inp.beg);
oup<<(char)inp.get();
************************************/
}
inp.close();
oup.close();
finish=clock();
FILE*p1=fopen("run_time.txt","a+");
fprintf(p1,"Time: %.3lf (s)-use cur\n",(double)(finish-start)/1000.0);//牵扯格式的我比较喜欢用C
fclose(p1);
system("run_time.txt");
std::cerr<<"\nOpen the file successfully\n";
return 0;
}
测试数据生成代码:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
freopen("out.txt","w",stdout);
long n=1000000;
while(n--)
{
putchar(65+rand()%26);//大写字母
}
return 0;
} C++ 文件 磁盘读写
[解决办法]
楼主,我觉得你程序的逻辑错了,导致了不公平的比较。
while(len>=0){
/******使用ios::cur寻址的代码********/
oup<<(char)inp.get();
inp.seekg(-2L,inp.cur);
len--;
/*******使用ios::beg寻址的代码********
inp.seekg(len--,inp.beg);
oup<<(char)inp.get();
************************************/
}
Time: 450.000 (s)-use cur
Time: 440.000 (s)-use cur
Time: 450.000 (s)-use cur
Time: 910.000 (s)-use beg
Time: 900.000 (s)-use beg
Time: 910.000 (s)-use beg
#include <stdio.h>
#include <string.h>
#include <conio.h>
FILE *fi,*fo;
int i;
int main(int argc,char **argv) {
if (argc<3) {
printf("Usage:%s src des\n",argv[0]);
return 1;
}
if (0==stricmp(argv[1],argv[2])) {
printf("Src and des is same!\n");
return 2;
}
fo=fopen(argv[2],"wb");
if (NULL==fo) {
printf("Can not create file %s\n",argv[2]);
return 3;
}
fi=fopen(argv[1],"rb");
if (NULL==fi) {
fclose(fo);
printf("Can not find file %s\n",argv[1]);
return 4;
}
i=0;
fseek(fi,-1L,SEEK_END);
while (1) {
fputc(fgetc(fi)^0x5A,fo);
i++;
if (i%1000000==0) cprintf("\r%dKB",i/1000);
if (fseek(fi,-2,SEEK_CUR)) break;
}
fclose(fi);
fclose(fo);
cprintf("\r%dKB OK.\r\n",i/1000);
return 0;
}