可以打开小的ASCII文件,但不能打开大的二进制文件吗?

mez*_*hic 10 c c++ file large-files c++11

我使用以下代码在Windows上的MSVC中打开一个大型(5.1GB)二进制文件.机器有足够的RAM.问题是长度被检索为零.但是,当我将file_path更改为较小的ASCII文件时,代码工作正常.

为什么我不能加载大型二进制文件?我更喜欢这种方法,因为我想要一个指向文件内容的指针.

FILE * pFile;
uint64_t lSize;
char * buffer;
size_t result;

pFile = fopen(file_path, "rb");
if (pFile == NULL) { 
    fputs("File error", stderr); exit(1); 
}

// obtain file size:
fseek(pFile, 0, SEEK_END);
lSize = ftell(pFile);                                // RETURNS ZERO
rewind(pFile);

// allocate memory to contain the whole file:
buffer = (char*)malloc(sizeof(char)*lSize);
if (buffer == NULL) {
    fputs("Memory error", stderr); exit(2); 
}

// copy the file into the buffer:
result = fread(buffer, 1, lSize, pFile);             // RETURNS ZERO TOO
if (result != lSize) {                               // THIS FAILS
    fputs("Reading error", stderr); exit(3); 
}

/* the whole file is now loaded in the memory buffer. */
Run Code Online (Sandbox Code Playgroud)

它不是文件权限或任何东西,它们没问题.

Rot*_*ces 1

数据类型 long 太小,无法表示文件大小。使用 stat() 方法(或特定于 Windows 的替代方法GetFileAttributes)读取文件大小。