gpt4 book ai didi

c - 如何消除段错误?

转载 作者:行者123 更新时间:2023-11-30 19:03:32 25 4
gpt4 key购买 nike

我已经研究这个问题很长时间了,但无法找出段错误的原因。

我感觉多次写入缓冲区有问题,但我不知道任何替代方法。或者可能是内存分配的问题。

这是代码。

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


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

FILE* file = fopen(argv[1], "r");

if(!file)
{
fprintf(stderr, "No file found\n");
return 2;
}

fseek(file, 0, SEEK_SET);

unsigned char buffer[512];

int counter = 0;

char imagename[8];

FILE* image;

while(fread(buffer, 512, 1, file) == 1)
{
if(buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[0] & 0xf0) == 0xe0 )
{
if(counter > 0)
{
fclose(image);
}
sprintf(imagename, "%03i.jpg", counter);

image = fopen(imagename, "w");

if(!image)
{
fprintf(stderr, "No file found\n");
return 2;
}

fwrite(buffer, 512, 1, image);

printf("%i", counter);
counter++;

}

else if(counter > 0)
{
fwrite(buffer, 512, 1, image);
}

}
fclose(image);
fclose(file);
free(image);
return 0;
}

最佳答案

我没有收到任何段错误,但我认为您弄错了 fread 函数。

Return Value The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.

所以我不知道你是否进入了循环或者你期待一些不同的东西。

你可以这样做:while(fread(buffer, 512, 1, file))

关于c - 如何消除段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com