为什么sscanf不在这里工作?
我正在做一个基于c语言的习题集。源代码在编译时没有任何语法错误,我也非常确定这些符号。我试图使用GDB发现错误。这就是我在每次迭代中注意到tempstorage机会指向的地址的内容,但第一个int保持不变(即0)。 这是cs50课程中的recover.c问题。我已经在cs50 stackexchagne上发布了同一程序的早期版本,但答案没有多大帮助。多谢各位为什么sscanf不在这里工作?,c,scanf,cs50,C,Scanf,Cs50,我正在做一个基于c语言的习题集。源代码在编译时没有任何语法错误,我也非常确定这些符号。我试图使用GDB发现错误。这就是我在每次迭代中注意到tempstorage机会指向的地址的内容,但第一个int保持不变(即0)。 这是cs50课程中的recover.c问题。我已经在cs50 stackexchagne上发布了同一程序的早期版本,但答案没有多大帮助。多谢各位 /** * recover.c * * Computer Science 50 * Problem Set 4 * * Rec
/**
* recover.c
*
* Computer Science 50
* Problem Set 4
*
* Recovers JPEGs from a forensic image.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* sdcard = fopen("card.raw", "r");
// to check if the file is opened correctly or not
if ( sdcard == NULL)
{
printf("corrupted sd card");
return 1;
}
// file pointer to point to the temporary jpg
FILE* tempjpgg;
// for the nomenclauture of the jpg photos
char* jpegname = (char*)malloc(8);
// to read 512 bytes of data at a time from the sdcard
char* tempstorage = (char*)malloc(512);
int firstint;
int i = 0;
for (fread(tempstorage, 512, 1,sdcard); ; )
{
sscanf(tempstorage, "%d", &firstint); // to make the checking process easier
if ( firstint >= 0xffd8ffe0 && firstint <= 0xffd8ffef)
{
fclose(tempjpgg);
sprintf(jpegname, "%03d.jpg", i);
tempjpgg = fopen(jpegname, "w");
fprintf(tempjpgg, "%d", firstint);
fwrite( tempstorage, 508, 1, tempjpgg);
i++;
}
else if ( i != 0)
{
fprintf(tempjpgg,"%d", firstint);
fwrite(tempstorage, 508, 1, tempjpgg);
}
fread(tempstorage, 512, 1, sdcard);
}
return 0;
}
/**
*恢复
*
*计算机科学50
*习题集4
*
*从法医图像恢复JPEG。
*/
#包括
#包括
int main()
{
文件*sdcard=fopen(“card.raw”,“r”);
//检查文件是否正确打开
如果(SD卡==NULL)
{
printf(“损坏的sd卡”);
返回1;
}
//指向临时jpg的文件指针
文件*tempjpgg;
//对于jpg照片的命名
char*jpegname=(char*)malloc(8);
//从SD卡一次读取512字节的数据
char*tempstorage=(char*)malloc(512);
int firstint;
int i=0;
用于(fread(tempstorage,512,1,sdcard);)
{
sscanf(tempstorage,'%d',&firstint);//使检查过程更容易
如果(firstint>=0xffd8ffe0&&firstint是JPEG文件中以字符串或二进制值形式存储的数据中的整数值-是否有4个字节直接表示整数,而不是一个包含n位数字的字符串。对于SO上的CS50,有相当多的JPEG恢复程序问题。请尝试搜索SO'[CS50]jpeg是:q
'以查看其他人做了什么或问了什么(13个问题,包括你的问题)。首先,你以文本模式打开二进制文件。但这里真正的问题是,你在二进制文件中写入数字的文本表示法!此外,你还比较了无符号和有符号(0xffxxxxxx)…在将整数写入二进制时需要处理尾数。祝你好运…你需要初始化:FILE*tempjpgg=NULL;
否则第一次调用fclose(tempjpgg)
你会得到UB(很可能是崩溃)。您还严重缺乏对各种调用的错误检查,这些调用可能会失败。@PaulR:使用空指针调用fclose()
已经是UB。不要使用fopen()返回的非空值以外的任何东西调用fclose()
@JonathanLeffler:你当然是对的-OP需要在调用fclose()之前初始化为NULL并测试非NULL,在调用fclose()之后将文件指针设置为NULL。