小编uor*_*001的帖子

奇怪的行为:不同位置的相同代码,读取二进制文件失败

我在一小段代码上遇到了麻烦,我正在尝试读取一个二进制文件,如果我将此代码放在单独的文件上,构建并运行它,它会完美地读取该文件,但如果我输入相同的代码在函数内的较大项目中,它总是错误地读取数据(两次测试使用同一文件)。

这是单独项目上的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
    char* filename = (char*)"file.binary";
    FILE* file = fopen(filename, "rb");

    if (!file) {
        printf("Unable to open %s for reading. \n", filename);
        fclose(file);
        free(filename);
        exit(1);
    }

    fseek (file , 0 , SEEK_END);
    long size = ftell (file);
    rewind (file);

    printf("Number of bytes in the file is %ld \n", size);

    int version = 0;

    char* string = (char*)malloc(sizeof(char) * 3);
    fread(string, sizeof(char), 3, file);

    if (strcmp(string, (char*)"str")) {
        printf("%s …
Run Code Online (Sandbox Code Playgroud)

c binary file

2
推荐指数
1
解决办法
140
查看次数

标签 统计

binary ×1

c ×1

file ×1