我有下面的程序来计算文件的大小
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string line;
ifstream myfile ("C:\\Users\\7\\Desktop\\example\\text.txt",ios::in | ios::out |ios::binary);
if (!myfile){
cout<<"cannot open file";
exit (1);
}
while (!myfile.eof()){
getline(myfile,line);
cout<<line<<endl;
}
long l,m;
l=myfile.tellg();
myfile.seekg(0,ios::end);
m=myfile.tellg();
cout<<"size of text file is:";
cout<<(m-l)<<"bytes"<<endl;
myfile.close();
return 0;
}为了在text.txt文件中做更多的澄清,我从这个网站http://en.wikipedia.org/wiki/List_of_algorithms写了一些信息的副本,但它显示我0字节,为什么?怎么啦?
发布于 2010-10-25 01:22:39
从文件结束位置(m)中减去当前文件位置(l)即可得到大小。如果current- file -position位于文件的开头,这将按照您的预期工作,但由于您刚刚读取了文件的全部内容,因此(l)从文件的末尾“开始”。
只需使用(m)的值,而不是(m-l),因为文件总是从0开始。
(或者,在使用ftell获取(l)之前,使用fseek移动到文件的开头)
发布于 2010-10-25 01:29:12
#include <stdio.h>
int main(int argc, char** argv) {
FILE *f = fopen("x.txt", "r");
fseek(f, 0, SEEK_END);
printf("%ld\n", ftell(f));
fclose(f);
return 0;
}发布于 2010-10-25 01:26:05
while (!myfile.eof()){
getline(myfile,line);
cout<<line<<endl;
}读取整个文件,因此get指针已经位于文件的末尾。myfile.seekg(0,ios::end)不会移动它,因此m-l将返回0。
https://stackoverflow.com/questions/4009389
复制相似问题