gpt4 book ai didi

c - C 中未遇到文件结尾 (eof)

转载 作者:行者123 更新时间:2023-11-30 18:46:27 25 4
gpt4 key购买 nike

我正在尝试运行代码。除最后一张外,所有图像均按照规范正常运行。

前四个字节 (B) 重复如下:

b8 97 98 c5

未遇到文件结尾,因此发现最后一个图像已损坏。

编辑:

  1. 已经提到文件中有 50 张图像。
  2. 您可以从以下位置获取原始文件:http://cdn.cs50.net/2017/fall/psets/4/recover/card.raw

原代码如下:

// Recovers lost images (.jpeg) in a memory card

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

#define buffsize 10

// Function to check whether jpeg or not
int check_jpeg(unsigned char *argv) {
unsigned int v1 = (int)argv[0];
unsigned int v2 = (int)argv[1];
unsigned int v3 = (int)argv[2];
unsigned int v4 = (int)argv[3];
if (v1 == 0xff && v2 == 0xd8 && v3 == 0xff) {
switch (v4) {
case 0xe0:
case 0xe1:
case 0xe2:
case 0xe3:
case 0xe4:
case 0xe5:
case 0xe6:
case 0xe7:
case 0xe9:
case 0xea:
case 0xeb:
case 0xec:
case 0xed:
case 0xee:
case 0xef:
return 1;
break;
default:
return 0;
}
} else {
return 0;
}
}

int main(int argc, char *argv[]) {
// Cautioning the user for wrong usage
if (argc != 2) {
fprintf(stderr, "Usage: ./recover file\n");
return 1;
}

// Opens the .raw file to begin inspection
FILE *camera = fopen(argv[1], "r");

// Checks the validity of the opened file
if (camera == NULL) {
fprintf(stderr, "Error opening file: %s\n",argv[1]);
return 2;
}

int counter = 0; // Declaring and Initialising the counter
int online = 0; // To know whether image is being written

char *filename = (char*)malloc(buffsize);
FILE *outptr;

while (1) {
unsigned char *image = malloc(512);
if (image == NULL) {
fprintf(stderr, "Error creating pointer \n");
return 200;
}
fread(image, 512, 1, camera);
if (image != NULL) {
int flag = check_jpeg(image);
if (counter == 50) {
printf("%x %x %x %x\n", image[0], image[1], image[2], image[3]);
}
if (flag == 1) {
if (counter != 0) {
fclose(outptr);
}
counter++;

// Creating the output file pointer
snprintf(filename, buffsize - 1, "%03i.jpg", counter);
outptr = fopen(filename, "w");
if (outptr == NULL) {
fprintf(stderr, "Error opening file: %s\n", filename);
return 201;
}

// Writing to the file
fwrite(image, 512, 1, outptr);
online = 1;
} else
if (flag == 0 && online == 1) {
fwrite(image, 512, 1, outptr); // Continue writing to the output file
}
free(image);
} else {
fclose(camera);
fclose(outptr);
return 0;
}
}
}

最佳答案

您的代码中存在多个问题:

  • 您没有检查fread成功读取了多少数据。在文件末尾,fread 返回 0,否则 fread 返回成功读入目标数组的 block 数。要跟踪读取的字节,请传递 1 作为 block 大小,并传递 512 作为 block 数。
  • 没有真正需要分配文件名和输入/输出缓冲区,本地数组就可以满足您的目的。
  • 文件应以二进制模式打开:FILE *camera = fopen(argv[1], "rb");
  • snprintf 的第二个参数应该是缓冲区大小,而不是要写入的最大字符数:snprintf(filename, buffsize, "%03i.jpg", counter);

关于c - C 中未遇到文件结尾 (eof),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51650734/

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