我可以使用cs50对此pset的一些指导。下面是我到目前为止的代码。我被困在这一点,我不知道如何继续。当我运行该程序时,它输出16个jpg文件,但我无法查看它们,所以一定是错的。欢迎任何提示。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// create buffer to store in
unsigned char buffer[512];
// array for filename is 8 for "000.jpg"
char jpgName[8];
// declaring counter for amount of jpegs
int jpgcounter = 0;
// open memory card file
FILE* inptr = fopen("card.raw", "r");
FILE* outptr = NULL;
if (inptr == NULL)
{
printf("Could not open %s.\n", "card.raw");
return 1;
}
// repeat until end of card
while(fread(buffer, sizeof(buffer), 1, inptr) == 1)
{
// find beginning of jpg
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
{
// if allready a outptr file is open close it
if (outptr != NULL)
{
fclose(outptr);
}
// create filename for jpegs
sprintf(jpgName,"%03d.jpg", jpgcounter);
// open a new file with name defined by sprintf
FILE* outptr = fopen(jpgName, "w");
// write into the outfile from buffer
fwrite(&buffer, sizeof(buffer), 1, outptr);
// increment counter for jpegs
jpgcounter++;
}
}
fclose(inptr);
return 0;
}
答案 0 :(得分:0)
这无效:
while(fread(buffer, sizeof(buffer), 1, inptr) == 1)
{
// read 512 bytes from inptr and store them in buffer
fread(&buffer, sizeof(buffer) , 1, inptr);
当您使用fread
两次时,第一次读取的数据会被第二次覆盖。看起来好像丢失了原始文件中每个kB的前512个字节。
如果删除第二个fread(),你应该会更进一步。
答案 1 :(得分:0)
如果我理解你的任务正确,你想要这样的东西 - 请看下面的内容。 提示:如果不是jpg文件的开头,你打算做什么?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned char buffer[512] = {0};
char jpgName[8] = {0};
int jpgcounter = 0;
FILE* outptr = NULL;
// open memory card file
FILE* inptr = fopen("card.raw", "rb");
if (inptr == NULL)
{
printf("Could not open %s.\n", "card.raw");
return 1;
}
// Start reading
while(fread(buffer, sizeof(buffer), 1, inptr) == 1)
{
// Find beginning of jpg
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
{
if(NULL!=outptr)
{
fclose(outptr);
outptr=NULL;
}
// Create filename for jpegs
sprintf(jpgName,"%03d.jpg", jpgcounter);
// Open a new file with name defined by sprintf
outptr = fopen(jpgName, "wb");
if (NULL == outptr)
{
printf("Could not open %s.\n", jpgName);
return 1;
}
// Write into the outfile from buffer
fwrite(buffer, sizeof(buffer), 1, outptr);
// Increment counter for jpegs
jpgcounter++;
}
else
{
// Continue writing to old file if it is not beginning of file
if(NULL!=outptr)
fwrite(buffer, sizeof(buffer), 1, outptr);
}
}
if(NULL!=outptr)
fclose(outptr);
if(NULL!=inptr)
fclose(inptr);
return 0;
}