我正试图将一个小型数据分析程序从64位UNIX移植到32位Windows XP系统中(别问我为什么)。
但现在我遇到了2GB文件大小限制的问题(因为该平台上的long不是64位)。
我已经搜索了这个网站和其他网站,寻找可能解决我的问题的方法,但没有找到任何直接适用于我的问题的方法。 问题出现在fseek和ftell函数的使用上。
是否有人知道如何修改以下两个函数,使它们能够处理大于2GB(实际上为约100GB)的文件,且nsamples的返回类型必须是64位整数(可能是int64_t)。
我尝试使用以下代码替换nsamples来使用_fseeki64和_ftelli64:
我已经搜索了这个网站和其他网站,寻找可能解决我的问题的方法,但没有找到任何直接适用于我的问题的方法。 问题出现在fseek和ftell函数的使用上。
是否有人知道如何修改以下两个函数,使它们能够处理大于2GB(实际上为约100GB)的文件,且nsamples的返回类型必须是64位整数(可能是int64_t)。
long nsamples(char* filename)
{
FILE *fp;
long n;
/* Open file */
fp = fopen(filename, "rb");
/* Find end of file */
fseek(fp, 0L, SEEK_END);
/* Get number of samples */
n = ftell(fp) / sizeof(short);
/* Close file */
fclose(fp);
/* Return number of samples in file */
return n;
}
并且
void readdata(char* filename, short* data, long start, int n)
{
FILE *fp;
/* Open file */
fp = fopen(filename, "rb");
/* Skip to correct position */
fseek(fp, start * sizeof(short), SEEK_SET);
/* Read data */
fread(data, sizeof(short), n, fp);
/* Close file */
fclose(fp);
}
我尝试使用以下代码替换nsamples来使用_fseeki64和_ftelli64:
。
__int64 nsamples(char* filename)
{
FILE *fp;
__int64 n;
int result;
/* Open file */
fp = fopen(filename, "rb");
if (fp == NULL)
{
perror("Error: could not open file!\n");
return -1;
}
/* Find end of file */
result = _fseeki64(fp, (__int64)0, SEEK_END);
if (result)
{
perror("Error: fseek failed!\n");
return result;
}
/* Get number of samples */
n = _ftelli64(fp) / sizeof(short);
printf("%I64d\n", n);
/* Close file */
fclose(fp);
/* Return number of samples in file */
return n;
}
对于一个大小为4815060992字节的文件,我得到了260046848个样本(例如_ftelli64
给出的是520093696字节),这很奇怪。
有趣的是,当我在调用_fseeki64
时省略了(__int64)
转换时,我会得到运行时错误(无效参数)。
有什么想法吗?