gpt4 book ai didi

c - 从 FAT12 文件获取数据

转载 作者:行者123 更新时间:2023-11-30 19:16:50 24 4
gpt4 key购买 nike

对于初学者来说,这是一些家庭作业的一部分。作业是从 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;
}

我想说我的问题是一个指针问题,我只是不知道在哪里或如何。任何有关我的结果如何以及为何不稳定的见解将不胜感激。

最佳答案

不要尝试使用 fread 读取 int 的一部分。只需使用简单的方法即可,使用 getc 读取一个字节并返回它(或者如果没有更多字节可供读取,则返回 EOF - 如果您可以处理此问题)想要)。

int NumberFAT(FILE *fp)
{
fseek(fp,16L,SEEK_SET);
return getc(fp);
}

关于c - 从 FAT12 文件获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com