2010-02-17 49 views
10

我正在使用Linux和C++。我有一个大小为210732个字节的二进制文件,但seekg /所以tellg报告尺寸为210728.C++:获取不正确的文件大小

我从LS-LA,即210732个字节以下信息:

-RW -rw-R-- 1个PJS PJS 210732 02月17日10:25 output.osr

并与下面的代码片段,我得到210728:

std::ifstream handle; 
handle.open("output.osr", std::ios::binary | std::ios::in); 
handle.seekg(0, std::ios::end); 
std::cout << "file size:" << static_cast<unsigned int>(handle.tellg()) << std::endl; 

所以我的代码是关闭的4个字节。我已使用十六进制编辑器确认文件的大小是正确的。那么为什么我没有得到正确的尺寸?

我的答案:我认为这个问题是由于文件有多个开放的fstreams引起的。至少这似乎已经整理出来了。感谢所有帮助过我的人。

+0

这是在所有的文件系统的情况下(情况你有几个)? – hlovdal 2010-02-17 16:51:08

+0

不幸的是,我没有选择在不同的文件系统上测试。 – PSJ 2010-02-17 16:52:09

+0

适用于我的32位Ubuntu系统。你使用g ++吗? – tur1ng 2010-02-17 16:53:22

回答

3

至少对我用G ++ 4.1和4.4在64位CentOS 5上,下面的代码按预期工作,即程序打印的长度与stat()调用返回的长度相同。


#include <iostream> 
#include <fstream> 
using namespace std; 

int main() { 
    int length; 

    ifstream is; 
    is.open ("test.txt", ios::binary | std::ios::in); 

    // get length of file: 
    is.seekg (0, ios::end); 
    length = is.tellg(); 
    is.seekg (0, ios::beg); 

    cout << "Length: " << length << "\nThe following should be zero: " 
     << is.tellg() << "\n"; 

    return 0; 
} 
+0

谢谢。令人惊讶的是,这实际上给了我正确的答案。我不明白为什么,但它确实为我提供了我期待的结果。 – PSJ 2010-02-17 18:04:45

+0

但这是完全相同的代码,除了静态转换为无符号int – pm100 2010-02-17 18:10:38

+0

是的,我必须有某个地方,这是干扰。我试图弄清楚。 – PSJ 2010-02-17 18:13:00

9

为什么打开文件并检查大小?最简单的方法是做这样的事情:

 
#include <sys/types.h> 
#include <sys/stat.h> 

off_t getFilesize(const char *path){ 
    struct stat fStat; 
    if (!stat(path, &fStat)) return fStat.st_size; 
    else perror("file Stat failed"); 
} 

编辑:感谢PSJ您指出一个小错字故障... :)

+0

我注意到这是downvoted然后upvoted?为什么? – t0mm13b 2010-02-17 17:02:20

+1

可能是因为它没有回答 – 2010-02-17 17:03:34

+0

@ Neil:哦......他谈到了打开文件并寻求最终以获得大小,并返回不正确的结果......我想知道为什么不使用这个功能,而不是必须打开/关闭文件...? – t0mm13b 2010-02-17 17:05:32

1

ls -la是否有可能报告文件在磁盘上占用的字节数,而不是实际大小?这将解释为什么它略高。

+0

这也是我的想法。我自己生成文件,并且将210732字节放入文件中,当我使用ghex2检查文件时,它实际上包含所有字节。 – PSJ 2010-02-17 18:14:30

2

在Unix上的味道,为什么我们使用的是,当我们有统计utlilty

long findSize(const char *filename) 
{ 
    struct stat statbuf; 
    if (stat(filename, &statbuf) == 0) 
    { 
     return statbuf.st_size; 
    } 
    else 
    { 
     return 0; 
    } 
} 

如果不是,

long findSize(const char *filename) 
{ 
    long l,m; 
    ifstream file (filename, ios::in|ios::binary); 
    l = file.tellg(); 
    file.seekg (0, ios::end); 
    m = file.tellg(); 
    file.close(); 
    return (m – l); 
}