首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算文件大小

计算文件大小
EN

Stack Overflow用户
提问于 2010-10-25 01:19:20
回答 7查看 7.2K关注 0票数 0

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

代码语言:javascript
复制
#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字节,为什么?怎么啦?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-10-25 01:22:39

从文件结束位置(m)中减去当前文件位置(l)即可得到大小。如果current- file -position位于文件的开头,这将按照您的预期工作,但由于您刚刚读取了文件的全部内容,因此(l)从文件的末尾“开始”。

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

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

票数 8
EN

Stack Overflow用户

发布于 2010-10-25 01:29:12

代码语言:javascript
复制
#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;
}
票数 2
EN

Stack Overflow用户

发布于 2010-10-25 01:26:05

代码语言:javascript
复制
while (!myfile.eof()){
   getline(myfile,line);
   cout<<line<<endl;
}

读取整个文件,因此get指针已经位于文件的末尾。myfile.seekg(0,ios::end)不会移动它,因此m-l将返回0。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4009389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档