为什么我得到段错误(二进制数据解析)c

时间:2015-04-18 23:14:09

标签: c segmentation-fault

我一次扫描512位字节的原始位。如果前4个字节与jpeg文件后缀匹配,我创建一个新的jpeg并将该块和所有后续块写入其中,直到遇到新的jpeg后缀。

由于某种原因,它会在第一次写入调用之后的读取调用中发生段错误。

/ **      * recover.c      *      *计算机科学50      *问题集4      *      *从法医图像中恢复JPEG。      * /

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

typedef uint8_t  BYTE;

int main(int argc, char* argv[])
{
    //load in file
    FILE* file = fopen("card.raw", "r");
    FILE* newfile = NULL;

    //error opening file
    if (file==NULL){
        return 1;
    }

    //create buffer and outfile index
    BYTE buffer[512]; //
    int filecount = 0;
    char newfilename[3];

    //iterate through file, break on eof
    while (1){//(!feof(file)){//(fgetc(file) != EOF){

        //seek back to 512 block start
        //fseek(file,-1,SEEK_CUR);
        //fread(&buffer,1,512,file);
        if (fread(buffer,512,1,file) <= 0){
            break;
        }

        //Check if first 4 bytes are jpeg signature
        if ((buffer[0] == 0xff &&
             buffer[1] == 0xd8 &&
             buffer[2] == 0xff &&
             buffer[3] == 0xe0)||
            (buffer[0] == 0xff &&
             buffer[1] == 0xd8 &&
             buffer[2] == 0xff &&
             buffer[3] == 0xe1 )){

            //close out previously created jpeg
            if (newfile != NULL){
                //file close error
                if (fclose(newfile) == EOF){
                    return 2;
                }
                newfile = NULL;
            }

            //create new jpeg
            sprintf(newfilename,"%03d.jpeg",filecount++);
            newfile = fopen(newfilename,"w");

        }

        //Write blocks to newfile
        if (newfile != NULL){
            if (fwrite(buffer,512,1,newfile) <= 0){
                return 4;
            }

        }
    }

    //close out last newfile 
    if (newfile != NULL){
        //file close error
        if (fclose(newfile) == EOF){
            return 3;
        }
        newfile = NULL;
    }

    //close infile
    fclose(file);



//we should find 16 images


}

1 个答案:

答案 0 :(得分:2)

的文件名数量不足
char newfilename[3];

当你做

sprintf(newfilename,"%03d.jpeg",filecount++);

需要

char newfilename[9];