这是我当前的代码。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int const BLOCK_SIZE = 512;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Incorrect usage\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
printf("Could not open the file\n");
return 1;
}
BYTE buffer[512];
int indx = 0;
int irratation= 0 ;
char* filename = malloc(10);
while(fread(buffer, 1, BLOCK_SIZE, file) == BLOCK_SIZE)
{
FILE* ptr = NULL;
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
irratation++;
if(irratation >= 2)
{
indx++;
}
if (indx == 0)
{
sprintf(filename, "%03i.jpg", indx);
ptr = fopen(filename, "w");
fwrite(buffer, 1, BLOCK_SIZE, ptr);
}
else
{
fclose(ptr);
sprintf(filename, "%03i.jpg", indx);
ptr = fopen(filename, "w");
fwrite(buffer, 1, BLOCK_SIZE, ptr);
}
}
else
{
fwrite(buffer, 1, BLOCK_SIZE, ptr);
}
}
return 0;
}
我想我明白它应该如何工作,并且我尝试从演练中实现伪代码,但我面临的问题是我不知道如何访问文件指针。我的意思是,如果我找到新文件,那么我说 ptr = fopen 并在那里写,但是当我找到下一个文件时,我无法关闭前一个文件,当我找不到时, else 语句也是如此新文件 - 我无法写入已打开的文件,因为它位于另一个 if 语句中。
你们能给我一些建议吗?
首先,图像由多个 512 大小的块组成,您要做的就是将每 512 字节写入一个新文件。
其次,刺激变量代表什么。如果您考虑一下,每次在 if 语句中找到要检查的 jpeg 前缀时,您都可以增加索引,这样就可以了,您所做的是(在修复文件问题之后)irratation首先设置为0,在while条件下,fread读取512字节,irratation加1,index不加1。索引为零,它找到 jpeg 前缀并写入新文件。现在循环重新开始,想想会发生什么,irratation 真的做了什么吗?
还有一件小事,你的文件名是“###.jpg”,你能再算一下你需要多少空间吗?别忘了‘’!
我试图尽可能多地暗示考虑 CS50 学术诚实和规则,所以试着弄清楚这一点!