首先,对于初学者来说,这是一些功课的一部分。赋值是从FAT12文件中获取数据。 我的问题是,当我运行我的代码时,我得到了从我的函数返回的虚假值(巨大的负数)。但是,如果我只运行一个或两个函数,我会得到正确的值。
我的职能: 我的函数遵循相同的模式,只是在fseek和fread中有不同的偏移量。
void getOSName(FILE *fp, char *osname)
{
fseek(fp,3L,SEEK_SET);
fread(osname,1,8,fp);
}
int totalSize(FILE *fp)
{
int *tmp1 = malloc(sizeof(int));
int *tmp2 = malloc(sizeof(int));
if (tmp1 == 0 || tmp2 == 0)
{
printf("Malloc of tmp in function 'totalSize' failed\n");
exit(0);
}
int retVal;
fseek(fp,0xb,SEEK_SET);
fread(tmp1,1,2,fp);
fseek(fp,0x13,SEEK_SET);
fread(tmp2,1,2,fp);
if (tmp2 == 0)
{
// pverflow, value is larger than 65535 blocks
//looking in offset
printf("In tmp2 IF\n");
fseek(fp,0x20,SEEK_SET);
fread(tmp2,1,2,fp);
}
retVal = *tmp1 * (*tmp2);
free(tmp1);
free(tmp2);
return retVal;
}
int NumberFAT(FILE *fp)
{
int *tmp1 = malloc(sizeof(int));
if (tmp1 == 0)
{
printf("Malloc of tmp in function 'NumberFAT' failed\n");
exit(0);
}
int retVal;
fseek(fp,16L,SEEK_SET);
fread(tmp1,1,1,fp);
retVal = *tmp1;
free(tmp1);
return retVal;
}
主要功能
int main(int argc, char *argv[])
{
FILE *fp = FileIn(argc,argv,"r");
char *osname = malloc(sizeof(char)*8);
if (osname == 0 )
{
printf("Malloc Failed\n");
exit(0);
}
int size,size2, Filenumb, FATnumb, FATsec;
getOSName(fp,osname);
printf("OS Name: %s\n", osname);
size = totalSize(fp);
printf("Total size of disk: %d\n", size); //always returns correct value
size2 = freeSpace(fp);
printf("Free size of the disk: %d :: %d\n",size-size2,size2); //Value is wrong due to incorrect logic
printf("==============\n");
Filenumb=numberFiles(fp);
printf("The number of files in the root directory (not including subdirectories): %d\n",Filenumb); //should get 3, get 224 by itself, 2144599840 with other functions
printf("\n==============\n");
FATsec=NumberFAT(fp);
printf("Number of FAT copies: %d\n",FATsec); //should and do get 2 by itself, -214400062 with other functions
FATnumb=Sectors(fp);
printf("Sectors per FAT: %d\n",FATnumb); // should and do get 9 by itself, -21400055 with other functions
free(osname);
fclose(fp);
return 0;
}
我想说我的问题是一个指针问题,我只是看不到在哪里或如何。 任何关于如何以及为什么我的结果不稳定的见解将非常感激。
答案 0 :(得分:1)
请勿尝试使用int
阅读部分fread
。只需使用getc
以简单的方式执行此操作,它会读取一个字节并返回它(如果没有更多要读取的字节,则返回EOF
- 如果需要,可以处理它。)
int NumberFAT(FILE *fp)
{
fseek(fp,16L,SEEK_SET);
return getc(fp);
}