【发布时间】:2016-04-23 15:16:20
【问题描述】:
我一直在为哈佛 CS50 课程解决问题集,我们的任务是从存储卡中恢复 jpeg。该卡按顺序存储 jpg。在编写我的程序时,我决定使用 while 循环来保持循环直到 EOF,但是使用课程中包含的调试器,我发现我的循环永远不会启动。我在下面包含了我的代码,我真的希望有人可以帮助我了解我在循环中出错的地方。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char* argv[])
{
// Ensure proper Usage
if (argc != 1)
{
printf("This file takes no input commands!\n");
return 1;
}
// open up card data file
FILE* dataFile = fopen("card.raw", "r");
if (dataFile == NULL)
{
char* invalidFile = "card.raw";
printf("Could not open %s.\n", invalidFile);
return 2;
}
// Create variable to keep track of num of output files written
int numFiles = 0;
// Create buffer
int* buffer = (int*)malloc(sizeof(int*) * 512);
// Create new file conditions
bool a = buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff;
bool b = buffer[3] == 0xe0 || buffer[3] == 0xe1|| buffer[3] == 0xe2 ||
buffer[3] == 0xe3 || buffer[3] == 0xe4 || buffer[3] == 0xe5 ||
buffer[3] == 0xe6 || buffer[3] == 0xe7 || buffer[3] == 0xe8 ||
buffer[3] == 0xe9 || buffer[3] == 0xea || buffer[3] == 0xeb ||
buffer[3] == 0xec || buffer[3] == 0xed || buffer[3] == 0xee ||
buffer[3] == 0xef;
// Loop through until all files found
while(fread(&buffer, 512, 1, dataFile) == 1)
{
if(a && b)
{
// Create temporary storage
char title[999];
// print new file name
sprintf(title, "%d.jpg", numFiles);
// open new file
FILE* img = fopen(&title[numFiles], "a");
numFiles = numFiles + 1;
fwrite(&buffer, sizeof(buffer), 1, img);
free(buffer);
}
else
{
if(numFiles > 0)
{
}
}
}
}
【问题讨论】:
-
如果您阅读
fread的手册页,您会注意到它的返回值是已读取的字节数。这就是你的问题之一。让我将另一个改写为:为什么你认为一旦你开始循环,a或b将有任何其他值,而不是你在循环之前分配给它们的值. -
聪明的你! C 不是解释器,因此
bool a = ...被评估一次然后使用。但是您希望每次都对其进行评估。然后你在一个带有随机值的缓冲区上评估它!回去学习你的课程材料。 -
@Mathstudent "fread(&buffer, 512, 1, dataFile)" 的返回值是什么?
-
嘿,感谢 cmets!我的理解是 fread 每次循环都会返回 1,这与 nmemb(3rd entry) 相同。我的文件头条件是我刚刚添加的,我将把它改回原来的方式。
标签: c while-loop cs50