我需要determin一个文件的字节大小。

的编码语言为C ++和代码应该与Linux,Windows和任何其他操作系统工作。这意味着使用标准的C或C ++函数/类。

此琐碎需要显然已经没有平凡解。

有帮助吗?

解决方案

使用std的流可以使用:

std::ifstream ifile(....);
ifile.seekg(0, std::ios_base::end);//seek to end
//now get current position as length of file
ifile.tellg();

如果你处理只写文件(的std :: ofstream的),那么方法有一些其他:

ofile.seekp(0, std::ios_base::end);
ofile.tellp();

其他提示

可以使用stat系统调用:

#ifdef WIN32 
_stat64()
#else
stat64()

如果您只需要在文件大小这无疑是矫枉过正,但一般我会用的 Boost.Filesystem的以独立于平台的文件操作。 除了其他属性功能它包含

template <class Path> uintmax_t file_size(const Path& p);

您可以找到参考这里。虽然Boost库看似庞大,我发现它通常实现的东西非常有效。你也可以只作为升压是相当复杂的提取所需的功能但是这可能证明困难。

Simples:

std::ifstream ifs; 
ifs.open("mybigfile.txt", std::ios::bin); 
ifs.seekg(0, std::ios::end); 
std::fpos pos = ifs.tellg();

通常我们想要得到的东西中最便携的方式进行,但在某些情况下,尤其是这样的,我会强烈建议使用系统的API以获得最佳性能。

可移植性要求使用最少的共同点,这将是C.(不是C ++) 我使用的方法如下所述。

#include <stdio.h>

long filesize(const char *filename)
{
FILE *f = fopen(filename,"rb");  /* open the file in read only */

long size = 0;
  if (fseek(f,0,SEEK_END)==0) /* seek was successful */
      size = ftell(f);
  fclose(f);
  return size;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top