【发布时间】:2020-06-10 05:34:19
【问题描述】:
我需要从存储卡中恢复 jpeg 文件(原始数据)。我已经完成了下面的代码,但是我遇到了一个无法识别来源的段错误。总结一下,我做了一个循环来读取 512 字节的块并寻找特定的 jpeg 标头。如果它是第一个 jpeg,程序将打开一个文件并继续写入。如果 jpeg 不是第一个,关闭前一个图像并继续写入它。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
// Check usage
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
// Open file
FILE *file = fopen(argv[1], "r");
if (!file)
{
fprintf(stderr, "Could not open %s.\n", argv[1]);
return 1;
}
// open array to store the chunks with enough memory
unsigned char buffer [512];
// variables jpeg count
int img_count = 0;
// open filename img to write to
char filename[8];
FILE *img = NULL;
// create loop to read 512 chunks
while (fread(buffer, 512, 1, file) > 0)
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// if theres already a jpeg open
if (img_count > 0)
{
fclose(img);
sprintf(filename, "%i03.jpg", img_count);
img = fopen(filename, "w");
img_count++;
} // first jpeg img count == 0
else if (img_count == 0)
{
sprintf(filename, "%i03.jpg", img_count);
img = fopen(filename, "w");
img_count++;
}
}
//if this is not a new jpeg header, just write to img
if (img_count > 0)
{
fwrite(buffer, 512, 1, img);
}
else
{
continue;
}
}
fclose(img);
fclose(file);
return 0;
}
【问题讨论】:
-
valgrind 也显示“/etc/profile.d/cli.sh: line 94: 19528 Segmentation fault” 但我在第 94 行没有任何内容
-
imgoffwrite(buffer, 512, 1, img)不是有效的 FILE 指针。在调用fwrite之前,您的代码不会执行fopen。我在您的代码中添加了一些printfs,您可以在此处使用link 看到它。只需单击“开始”即可编译代码并在终端中运行。 -
谢谢。我已经修改为在 img_count == 0 (第一个 jepg)时添加 else if,如果没有检测到标题,则添加另一个 if 写入文件。我不再遇到段错误,但似乎我无法提取任何图像(说找不到 jpg)。新修改的代码如上。
-
我想不通。