c - fread/ftell 显然在 Windows 下损坏,在 Linux 下工作正常

标签 c windows linux file-io

问题来了,我正在为我的游戏读取关卡文件,在 linux 下运行良好:

@0
@12
200x200 version 3
@16
973 blocks
@989
@993
18 zones

但是在windows下我得到如下结果:

@0
@212
200x200 version 3
@216
973 blocks
@1200
@1204
18 zones

呃? Windows ftell 统计数据的偏移量为 200?读取文件显然会产生相同的数据,但 fread 使用(?) ftell 的值来确定文件中剩余多少字节可以读取。所以当然我在阅读文件末尾时遇到了问题:

@1425
zone#9 2x3 @ 66/9
@1425
zone#10 2x3 @ 66/9
@1425
zone#11 2x3 @ 66/9
@1425
zone#12 2x3 @ 66/9
@1425
zone#13 2x3 @ 66/9
@1425
zone#14 2x3 @ 66/9
etc.

这是相应的代码(由于所有调试打印,目前有点难看..):

void fread_all(void *ptr, size_t size, size_t count, FILE *stream) {
    fread(ptr, size, count, stream);
    printf("@%ld\n", ftell(stream));
}


bool map_load(struct Map *map, const char *file_name) {
    FILE *fp = fopen(file_name, "r");
    if (fp != NULL) {
        fseek(fp, 0, SEEK_SET);
        printf("@%ld\n", ftell(fp));

        // Header
        int *header = (int*)calloc(sizeof(int), 3);
        fread_all(header, sizeof(int), 3, fp);
        printf("%dx%d version %d\n", header[0], header[1], header[2]);

        map->pos_x = 0;
        map->pos_y = 0;
        map->map_x = 0;
        map->map_y = 0;
        map->size_x = header[0];
        map->size_y = header[1];
        map_zones_remove(map);        
        free(header);

        // Blocks
        unsigned int *block_size = (unsigned int*)malloc(sizeof(unsigned int));
        fread_all(block_size, sizeof(int), 1, fp);
        printf("%d blocks\n", *block_size);

        unsigned char *block_data = (unsigned char*)calloc(sizeof(unsigned char), *block_size);
        fread_all(block_data, sizeof(unsigned char), *block_size, fp);

        unsigned char *tmp = map->blocks;
        map->blocks = rle_decode(block_data, *block_size);
        free(tmp);
        free(block_size);
        free(block_data);

        // Zones
        int *zone_count = (int*)malloc(sizeof(int));
        fread_all(zone_count, sizeof(int), 1, fp);
        printf("%d zones\n", *zone_count);

        int *d = (int*)calloc(sizeof(int), 6);
        for(int i = 0, l = *zone_count; i < l; i++) {
            fread_all(d, sizeof(int), 6, fp);
            map_zone_create(map, d[0], d[1], d[2], d[3], d[4], d[5]);
            printf("zone#%d %dx%d @ %d/%d\n", i, d[2], d[3], d[0], d[1]);
        }
        map_platforms_create(map);

        free(zone_count);
        free(d);
        fclose(fp);
        return true;
    }
    return false;
}

我真的不知道这里发生了什么。编译器为Linux下的Visual Studio 10和GCC 4.4。

最佳答案

以二进制模式打开文件:

FILE *fp = fopen(file_name, "rb");

在文本模式下,可能会进行翻译以匹配依赖于操作系统的编码,例如C 库的换行符。

关于c - fread/ftell 显然在 Windows 下损坏,在 Linux 下工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3187693/

相关文章:

c - 将数组分配给 C 中的结构值

c - forkall 没有按预期工作

windows - Windows 附带的字体许可证?

asp.net - 将 ASP.NET 项目移动到 .NET 4

c++ - 如何在 Windows C++ 上分离线程

linux - 获取 adb 日志并将其 grep 到 IF 语句中的字符串

c - 用于编译和生成 C 文件输出的 Shell 脚本文件

C 变量覆盖值

linux - git:编辑文件导致使用 git diff 时出现 ^M

c - linux串口编程读取返回垃圾数据