C 程序未终止

标签 c jpeg restore cs50

我使用c编程来获取存储卡上删除的jpeg数据(由文件card.raw表示)。我现在正在尝试恢复这些 jpeg 文件。 问题:我的代码可以编译,但不会终止。 我考虑了 while 循环的另一个条件,但不幸的是我不知道如何正确执行。 (尝试了 EOF 和 feof)

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

int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
    fprintf(stderr, "Usage: ./recover filename\n");
    return 1;
}

// open input file
FILE *inptr = fopen(argv[1], "r");
//error if unable to open
if (inptr == NULL)
{
    fprintf(stderr, "Could not open %s.\n", argv[1]);
    return 2;
}

//variables
char buffer[512] = {0};
char jpeg1[4] = {0xff, 0xd8, 0xff, 0xe0};
char jpeg2[4] = {0xff, 0xd8, 0xff, 0xe1};
int count = 0;
char name[8] = {0};
FILE *outfile;
int isopen = 0;

//do while end of file is not reached
while (fread(buffer,1, 512, inptr) > 0)
{
    //compare buffer to bytes
    if (memcmp(buffer, jpeg1,4) == 0    || memcmp(buffer, jpeg2,4) == 0)

    {
        //close old outfile if open
        if(isopen ==1)
        {
            fclose(outfile);
        }

        //name for next outfile
        count ++;
        sprintf(name, "%03d.jpg", count);

        //open outfile and catch errors
        outfile = fopen(name, "w");
        if (outfile == NULL)
        {
            printf("Error opening outfile.\n");
            return 3;
        }
        isopen = 1;

        // write the first 512 bytes
        fwrite(buffer, 1, 512, outfile);
    }
    //no new jpeg
    // if outfile is open
    if (isopen == 1)
    {
        fwrite(buffer, 1, 512, outfile);
    }

    //move reader of fread()
    fseek(inptr, 1, SEEK_SET);
}

//close files
fclose(inptr);
fclose(outfile);

// success
return 0;
}

最佳答案

无限循环。

删除

fseek(inptr, 1, SEEK_SET);

每次执行循环时,都会将文件指针重置为文件的开头。

<小时/>

PS:尽量避免使用魔数(Magic Number),例如 512。我会使用类似 #define NMEMB 512 的定义。

关于C 程序未终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46366066/

相关文章:

c - C 中的运算符优先级和结构定义

Python 3 ctypes 调用具有返回结构的函数因段错误而失败

c - 如何检查文件夹C中是否存在文件

c - 为什么wav文件头是0x4e0而不是0x0?

html - 如何动态地在网页中的图像上放置不同的图案。

PostgreSQL 恢复备份解决方案

c - 读取并解码 jpg 图片

ffmpeg - 使用 ffmpeg 创建 png 缩略图会出现错误消息 "error padding picture"

ios - 保存并恢复 UINavigation 堆栈以重新连接

mysql - 从转储文件恢复数据库时如何记录sql错误