Groups has a post about how to obtain the file size in a standard way. The post points out a way to get the file size by seek to the end of the file and tell the current location. However, many people have pointed out that this method has different performance in different systems.
#include <fstream>#include <iostream>int main(){ std::ifstream in("somefile", std::ios::binary | std::ios::in); in.seekg(0, ios::end); std::cout << "file size: " << in.tellg() << std::endl;}
Objection:
1. some systems (except UNIX, windows, Mac), such as mainframe systems (of course, we usually do not consider programming on PC), text file and binary file are different, text File cannot be opened either in binary or in text.
2. The file size obtained in binary mode is different from that obtained in text mode, mainly because of Text Translation. Line ending is defined differently on different systems. In Windows, it is "/R/N", and in UNIX, It is '/N ', on Mac, it is '/R '. Whether it is Line ending, it is '/n' After reading from the file '. The actual read size on Windows is smaller than the size on disk.
3. Fuzzy definition of file size. The file size may be the total size of the slice occupied by the files stored on disk, or the number of characters. The file may contain metadata, such as Bom. In case of BOM, fseek on Windows defines the data starting from the BOM, that is, the actual file content.
4. Using seek to end to obtain the file size cannot be transplanted. In UNIX file systems, many devices are treated as files, but the seek to end method is not supported. The size can only be determined after the content is read, such as/dev/tty.
5. The size obtained using seek to end may be greater than the actual size, because some padding may exist in the last part of the file, and the garbbage data may also be included.
Conclusion: To use seek to end to obtain the file size, it is feasible on Windows and UNIX. To obtain a more reasonable size, you can only call OS-specific functions, such as getfilesize * on Windows *.
Reference:
Http://groups.google.com/group/comp.lang.c++/browse_thread/thread/a91eb83ba0e8377f/d27c88e57faadeb5? Hl = en & # d27c88e57faadeb5