计算文件大小

dat*_*ili 0 c++

我有以下程序来计算文件的大小

#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;

}
Run Code Online (Sandbox Code Playgroud)

为了使text.txt文件更清晰,我已经从这个网站写了一些信息, http://en.wikipedia.org/wiki/List_of_algorithms 但它显示0字节,为什么?怎么了?

Jas*_*ams 8

您正在从文件结束位置(m)中减去当前文件位置(l)以获取大小.如果当前文件位置位于文件的开头,这将按预期工作,但是当您刚刚读取文件的全部内容时,(l)在文件末尾"开始".

只需使用(m)的值而不是(ml),因为文件总是从0开始.

(或者,在使用ftell获取(l)之前,使用fseek移动到文件的开头)