简体   繁体   English

在 windows 上的文件结束之前到达 EOF

[英]Reaching EOF before end of file on windows

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

const int size = 512;
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image\n");
        return 1;
    }

    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        fprintf(stderr, "Could not open file\n");
        return 1;
    }
    unsigned char buffer[size];
    int count = 0;
    FILE *jpeg = NULL;

    while(fread(buffer, size, 1, file))
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            char image[7];
            if (count != 0)
            {
                fclose(jpeg);
            }
            sprintf(image, "%03i.jpg", count);
            jpeg = fopen(image, "w");
            if (jpeg == NULL)
            {
                fprintf(stderr, "couldn't open file\n");
                return 1;
            }
            count++;
        }
        if (count != 0)
        {
            fwrite(&buffer, size, 1, jpeg);
        }
    }
    fclose(file);

}

This code look for jpeg in card.raw When i run above code on linux, its running correctly.此代码在 card.raw 中查找 jpeg 当我在 linux 上运行上述代码时,它运行正常。 but on windows code reads only first three block of 512 bytes of card.raw file.但在 windows 代码上仅读取 card.raw 文件的 512 字节的前三个块。 what i'm doing wrong?我做错了什么? also i'm using clang on linux.我也在 linux 上使用 clang。 and on windows i'm using gcc.在 windows 上,我使用的是 gcc。

Firstly, binary files should be opened with binary mode.首先,二进制文件应该以二进制模式打开。 This means you should use "rb" and "wb" for fopen() mode instead of "r" and "w" .这意味着您应该在fopen()模式下使用"rb""wb"而不是"r""w" Otherwise, newline characters may be unwantedly converted and they may stop at byte 0x1a .否则,换行符可能会被意外转换,并且可能会在字节0x1a处停止。

Secondly, doing sprintf(image, "%03i.jpg", count);其次,做sprintf(image, "%03i.jpg", count); for the array char image[7];对于数组char image[7]; is bad.不好。 The result of sprintf() will be (at least) 7 characters, so array with 8 elements or more is required to store the string including terminating null-character. sprintf()的结果将是(至少)7 个字符,因此需要具有 8 个或更多元素的数组来存储包含终止空字符的字符串。 for safety, you should use snprintf() , which accepts the buffer size.为了安全起见,您应该使用snprintf() ,它接受缓冲区大小。

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

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