Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

linux - C++: Getting incorrect file size

I'm using Linux and C++. I have a binary file with a size of 210732 bytes, but the size reported with seekg/tellg is 210728.

I get the following information from ls-la, i.e., 210732 bytes:

-rw-rw-r-- 1 pjs pjs 210732 Feb 17 10:25 output.osr

And with the following code snippet, I get 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;

So my code is off by 4 bytes. I have confirmed that the size of the file is correct with a hex editor. So why am I not getting the correct size?

My answer: I think the problem was caused by having multiple open fstreams to the file. At least that seems to have sorted it out for me. Thanks to everyone who helped.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why are you opening the file and checking the size? The easiest way is to do it something like this:

#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");
}

Edit: Thanks PSJ for pointing out a minor typo glitch... :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...