C程序没有终止

时间:2017-09-22 13:33:11

标签: 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;
}

1 个答案:

答案 0 :(得分:2)

你无限循环。

删除

fseek(inptr, 1, SEEK_SET);

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

PS:尽量避免使用魔法数字,例如512.我会使用类似#define NMEMB 512的定义。