C. fread适用于Linux但不适用于Windows

时间:2016-05-24 23:16:49

标签: linux windows

在linux上,这段代码可行。它从文件读取50000个int(文件大小= 200000字节)。但在视觉工作室2015年,fread返回73。 我不明白为什么?

控制台:

Oops. Can not read successfully the stack.
 size = 50000
rsize = 73
filename = nums
Size of int = 4
Better to STOP
Press any key to continue . . .

代码段:

FILE* f = fopen(fn, "r");
if (f == NULL)
{
    printf("\nCan not open file  %s\n", fn);
    return 1;
}

int* stack = malloc(sizeof(int) * size);
if (stack == NULL)
{
    fclose(f);
    printf("\nCan not stack the stack - not enough memory\n");
    return 2;
}


int rsize = fread(stack, sizeof(int), size, f);
if (size != rsize)
{
    printf("\nOops. Can not read successfully the stack.\n size = %d\nrsize = %d\nfilename = %s\nSize of int = %d\nBetter to STOP\n", size, rsize, fn, sizeof(int));
    fclose(f);
    free(stack);
    return 3;
}

1 个答案:

答案 0 :(得分:2)

您可能需要设置二进制模式" rb"打开文件时,否则它将作为文本文件(在Windows中)与Linux中的二进制文件打开。