c - CS50 RECOVER 寻找迭代条件语句
问题描述
大家好,这是一个CS50作业,它假设通过C的文件处理功能从存储卡中恢复一堆照片。它恢复了第一张照片(即000.jpeg)但是当涉及到继续新的jpeg时它只能写一个块(512BYTE)一次然后停止。我正在寻找一个条件让它自动化(参考上面的 printf("I can write to the new jpeg\n");) 与 while 循环但 isjpeg() 函数不可操作,因为它具有相同的开头(不知道为什么,但尝试不起作用)。我正在寻找一种延续它的方式。感谢所有帮助赞赏。
(这是终端上的输出,以便您看到结果,为了便于演示,减少了 I could not found new 的数量。)
$ ./recover card.raw
I could not found a new so keep goin
I could not found a new so keep goin
I can found the first jpeg
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I can write to the new jpeg
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef unsigned char BYTE;
int main(int argc, char *argv[])
{
int jpegnumber; jpegnumber = 0;
bool isjpeg();
bool jpeghasfound = false;
char filename[8];
if (argc != 2 )
{
printf("Program should have one command line argument \n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
return 1;
BYTE buffer[512];
FILE* img;
while (fread(buffer, 512, 1, file)) // if it reads something
{
if ( isjpeg(buffer) && (!jpeghasfound) ) // it founds a jpeg first time
{
jpeghasfound = true;
sprintf(filename,"%03i.jpg",jpegnumber);
img = fopen(filename,"w");
printf("I can found the first jpeg\n\n");
if (img == NULL)//nullcheck
{
printf("There is nothing to open \n");
return 1;
}
fwrite(buffer,512,1,img);
jpegnumber++; // increment the count
}
else if (isjpeg(buffer) && jpeghasfound) // Founding a new jpeg
{
fclose(file); // close old file
sprintf(filename,"%03i.jpg",jpegnumber);
if (img == NULL)//nullcheck
{
printf("There is nothing to open \n");
return 1;
}
fwrite(buffer,512,1,img);
printf("I can write to the new jpeg\n");
}
else // if we have not find a new jpeg we should keep writing to old file
{
fwrite(buffer,512,1,img);
printf("I could not found a new so keep goin\n");
}
}
fclose(file);
fclose(img);
}
bool isjpeg(BYTE buffer[])
{
if((buffer[0] == 0xff ) && (buffer[1] == 0xd8 ) && (buffer[2] == 0xff ) && ((buffer[3] & 0xf0 ) == 0xe0))
{
return true;
}
else
{
return false;
}
}
解决方案
推荐阅读
- go - time.Tick 终端失去焦点时停止工作
- flutter - 根据数据对颤振小部件进行分组
- angular - Angular HashLocationStrategy 包含目录名称
- bash - 无法通过传递动态值 bash 脚本进行过滤
- sql-server - 我应该在插入大量数据之前还是之后创建索引?
- python - 没有在 Django 中调用 process_template_response
- sql - 排序填充值
- slider - 如何阻止轻弹在移动视口中跳跃
- inline - 我可以将 pragma `Inline` 放在正文中而不是规范中吗?
- java - 用另一个 Spark Java 替换一列值