-1

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

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

4

1 回答 1

1

不要试图阅读intwith的一部分fread。只需使用简单的方法, with getc,它读取一个字节并返回它(或者EOF如果没有更多字节要读取,则返回 - 如果你愿意,你可以处理)。

int NumberFAT(FILE *fp)
{
    fseek(fp,16L,SEEK_SET);
    return getc(fp);
}
于 2015-03-27T03:00:32.570 回答