再一次,我正在尝试编写一个从 .raw 文件复制 jpeg 的程序。它发现第一个标头(0xffd8ffe0 或 0xffd8ffe1)正常,然后继续将标头写入 outptr,然后继续以 512 位块复制 jpeg 数据。我尝试编写 do-while 循环,以便它读取 512 位数组并检查每个数组以确保它不包含新标头(在数组的前四个字节中),这将使它停止并再次启动while循环,复制下一个,但它似乎永远不会找到另一个标题,即使我知道它在那里,它应该立即出现在最后一个512位块之后。
#include <stdio.h>
#include <stdint.h>
#define READFILE "/home/cs50/pset5/card.raw"
int
main(void)
{
// open readfile
FILE *inptr = fopen(READFILE, "r");
if (inptr == NULL)
{
printf("Could not open file.\n");
return 1;
}
while (feof(inptr) == 0)
{
// counter for writefilename
int writeCounter = 0;
// find a header by iterating until it finds a 0xff
int byte[4];
if (byte[0] != 0xff)
byte[0] = fgetc(inptr);
else
{
// then check if the next byte is 0xd8, if not, look for the next 0xff
byte[1] = fgetc(inptr);
if (byte[1] != 0xd8)
break;
else
{
// then check if the next byte is 0xff, if not, ditto
byte[2] = fgetc(inptr);
if (byte[2] != 0xff)
break;
else
{
// then check if the next byte is 0xe0 or 0xe1, if not, ditto
byte[3] = fgetc(inptr);
if (byte[3] == 0xe0 || byte[3] == 0xe1)
{
// since it's a header, start writin'
// open writefile
char filename[7];
sprintf(filename, "0%.2d.jpg", writeCounter);
FILE *outptr = fopen(filename, "w");
writeCounter++;
// replace byte[0] since sprintf seems to make it 0 for some reason
byte[0] = 0xff;
// write the header that's in array byte[]
fwrite(&byte, 4, 1, outptr);
// write pixels in 64-byte chunks until a new header is found
char pixel[64];
do
{
fread(&pixel, 64, 1, inptr);
if (pixel[0] == 0xff && pixel[1] == 0xd8 && pixel[2] == 0xff && (pixel[3] == 0xe0 || pixel[3] == 0xe1))
{
fseek(inptr, -64, SEEK_CUR);
break;
}
else
fwrite(&pixel, 64, 1, outptr);
} while (pixel[0] != 0xff && pixel[1] != 0xd8 && pixel[2] != 0xff && (pixel[3] != 0xe0 || pixel[3] != 0xe1));
}
else
break;
}
}
}
}
}