简体   繁体   English

fread()返回不正确的数据

[英]fread() returns incorrect data

I am trying to read 128KB binary file in chunks of 256 Bytes. 我正在尝试以256字节的块读取128KB二进制文件。 The first 20-40 bytes of 256 bytes seems to be always correct. 256个字节的前20-40个字节似乎总是正确的。 However after that the data gets corrupted. 但是,此后数据将被破坏。 I tried reading the file and writing it into another binary file and compared. 我尝试读取文件并将其写入另一个二进制文件并进行比较。 More than half of the data is corrupted. 一半以上的数据已损坏。 Here is my code 这是我的代码

uint8_t buffer[256]
read_bin_file = fopen("vtest.bin", "r");
if (read_bin_file == NULL)
{
    printf("Unable to open file\n");
    return false;
}

test_bin = fopen("test_file.bin", "w");
if (test_file == NULL)
{
    printf("Unable to open file\n");
    return false;
}

fflush(stdout);

for (i = 0; i <=0x1FF; i++)
{
    file_Read_pointer = i * 256;
    fseek(read_bin_file, file_Read_pointer, SEEK_SET);
    fread(buffer, 256, 1, read_bin_file);
    fseek(test_file, file_Read_pointer, SEEK_SET);
    fwrite(buffer, 256, 1, test_file);

}

What is that I am missing? 我想念的是什么? Also when i try to increase the bytes read from 256 to 1024 ( i<0x7F) the error seems to decrease significantly. 另外,当我尝试将读取的字节数从256增加到1024(i <0x7F)时,错误似乎也明显减少。 The file is almost 90% matching 文件几乎匹配90%

If it is binary data you're reading and writing, then you should open the files in binary mode with read_bin_file = fopen("vtest.bin", "rb"); 如果要读取和写入的是二进制数据,则应使用read_bin_file = fopen("vtest.bin", "rb");以二进制模式打开文件read_bin_file = fopen("vtest.bin", "rb"); . Note the "b" in the mode. 注意模式中的“ b”。 This prevents special handling of new line characters. 这样可以防止对换行符进行特殊处理。

Your fseek s are also unnecessary, the fread and fwrite calls will handle that for you. fseek也是不必要的, freadfwrite调用将为您处理。 From here "The file position indicator for the stream is advanced by the number of characters read." 此处开始 “流的文件位置指示符将按读取的字符数前进。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM