我在尝试正确执行以下代码时遇到问题。问题是我正在创建精确的JPEG数量,并且它们似乎正确打开,除了没有显示图像。我在CS50课程中正在做Pset4的recover.c。
/**
* A file that recovers lost JPEGs
*/
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
#define BLOCK 512
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
// remember filenames
char *infile = argv[1];
// open file
FILE* inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 2;
}
FILE* outptr;
uint8_t buffer[512];
int count = 0;
while (fread(buffer, BLOCK, 1, inptr))
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
&& (buffer[3] == 0xe0 || buffer[3] == 0xe1))
{
char filename[8];
sprintf(filename, "%03d.jpg", count);
outptr = fopen(filename, "w");
count++;
fwrite(&buffer, BLOCK, 1, outptr);
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", filename);
return 3;
}
}
}
fclose(outptr);
fclose(inptr);
return 0;
}
答案 0 :(得分:1)
图像无法正确打开,因为您只能将最多512个字节复制到每个文件中,而且我将假设大多数图像都大于此。
此代码:
outptr = fopen(filename, "w");
必须在外部 while(fread())
循环,你只想打开每个输出文件一次,而不是每个读取块打开一次。
此外,fread()
的返回值在这里非常重要,I / O应该是二进制的。
答案 1 :(得分:0)
没关系,我修复了代码,找到了问题的答案。如果有人感兴趣的话,这就是代码:感谢所有帮助过的人!
/**
* A file that recovers lost JPEGs
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BLOCK 512
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
// remember filenames
char *infile = argv[1];
// open file
FILE* inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 2;
}
FILE* outptr;
uint8_t buffer[512];
int count = 0;
// find lost images and write to outfile
while (fread(buffer, BLOCK, 1, inptr))
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
&& (buffer[3] == 0xe0 || buffer[3] == 0xe1))
{
char filename[8];
sprintf(filename, "%03d.jpg", count);
outptr = fopen(filename, "w");
count++;
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", filename);
return 3;
}
}
if (outptr != NULL)
{
fwrite(&buffer, BLOCK, 1, outptr);
}
}
fclose(outptr);
fclose(inptr);
return 0;
}