我是一个非常新手的程序员,我遇到了一个我不理解的问题,同时处理优秀的cs50课程的问题集。我已经实现了一个程序来从存储卡的图像中恢复JPEG图像,并在文件结束时实现中断,如下所示:
if(file > 1)
{
if (fread(&buffer, 1, 512, in_pointer) != 512)
{
free(filename);
return 0;
}
else
fseek(in_pointer, -512, SEEK_CUR);
}
(图片以512字节块填充卡片)。当我第一次实现它时,它打破了我的第一张图片(它是可识别但扭曲的)所以我通过第一个if语句排除它。然而现在该集合的中间文件略有偏离 - 它们仍然以Jpegs打开但我无法使其缩略图起作用。我的假设是我正在破坏JPEG文件格式标题。开始(包括集合的第一个和最后一个图像完美地工作)。 我的问题是:
由于我的getto解决方案造成了麻烦,实现EOF中断的优雅方法是什么?
我创造的问题的可能性是什么(用外行的话来说)?
非常感谢,
吉洪
ps这就是整件事
#include <cs50.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "enter exactly two command line arguments: ./recover and destination of disc to scan\n");
return 1;
}
//name the file
char *infile = argv[1];
//open card file and ensure proper format
FILE *in_pointer = fopen(infile, "r");
if (in_pointer == NULL)
{
fprintf(stderr, "could not open %s\n", infile);
return 2;
}
typedef uint8_t BYTE;
BYTE buffer[512];
bool new_jpeg = false;
int block = 0;
int file = 0;
char *filename = malloc(3);
//sprintf(filename, "%03i.jpg",1);
do
{
//read a 512 block of a jpeg
fread(&buffer, 512, 1, in_pointer);
//check for new jpeg
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0) // took me a while to figure this out
{
new_jpeg = true;
//printf("jpeg found, block %i\n", block);
}
block++;
} while(new_jpeg == false);
do
{
//set name of file to write to
sprintf(filename, "%03i.jpg",file);
file++;
new_jpeg = false;
// open output file
FILE *img = fopen(filename, "w");
if (img == NULL)
{
fprintf(stderr, "Could not create %s.\n", filename);
return 3;
}
//add blocks to file while before we reach the nea JPEG.
do
{
fwrite(&buffer, 1, 512, img);
//read the next block
fread(&buffer, 1, 512, in_pointer);
//There MUST be a better way... Anyhow this checks for end of file but backtracks becouse the act of checking moved the file coursor forward...
if(file > 1)
{
if (fread(&buffer, 1, 512, in_pointer) != 512)
{
free(filename);
return 0;
}
else
fseek(in_pointer, -512, SEEK_CUR);
}
block++; //we are reading off teh next block
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0) // took me a while to figure this out
{
new_jpeg = true;
//printf("jpeg %i found, block %i\n", file, block);
}
}while(new_jpeg == false);
}while(!feof(in_pointer));
free(filename);
//ran valgrind no probs detected.
}
答案 0 :(得分:0)
好的,我修好了。
我没有用完整的单独代码来检查eof,而是在一块石头上杀死了两只鸟,然后在检查eof时抓住文件:
export class HomePage {
posts: any;
constructor(public http: Http) {
this.http.get('https://www.reddit.com/r/gifs/new/.json?limit=10').map(res => res.json()).subscribe(data => {
this.posts = data.data.children;
});
}
}
我仍然不知道为什么我以前的方法不起作用,我会非常感激建议......