Reputation: 155
I'm having amazing difficulties using the fread and fwrite functions in C++.
The project is writing a rudimentary FAT16 file system and we are restricted to using fread and fwrite.
When I am initially writing the file my code looks like this:
directoryTable = (directoryEntry *)malloc(clusterSize);
for (int i = 0; i < bootRecord[0] / 128 ; ++i){
directoryEntry * newEntry = (directoryEntry *)malloc(sizeof(directoryEntry));
newEntry->name = (char *)malloc(112);
newEntry->name[0] = 'a'
write(1, &(newEntry->name[1]), 1);
newEntry->size = 0;
newEntry->type = 0;
newEntry->creation = 0x0000;
newEntry->index = 0;
fwrite(newEntry->name, 112, 1, fp);
fwrite(&newEntry->size, sizeof(int), 1, fp);
fwrite(&newEntry->type, sizeof(int), 1, fp);
fwrite(&newEntry->creation, sizeof(int), 1, fp);
fwrite(&newEntry->index, sizeof(int), 1, fp);
directoryTable[i] = *newEntry;
}
When I'm assigning the first character of directoryEntry->name to 'a', my intent is actually to assign it the value 0x00 so I can check later if it's null. I simply am using a right for debugging purposes. My problem is when I read it, I get nothing back.
And when I'm reading my code looks like this:
fseek(fp, clusterSize * root, SEEK_SET);
for(int i = 0; i < clusterSize / 128; ++i){
directoryEntry * newEntry = (directoryEntry *) malloc(128);
newEntry->name = (char *) malloc(112);
fread(newEntry->name, 112, 1, fp);
write(1, newEntry->name[0],1);
fread(&newEntry->size, sizeof(int), 1, fp);
fread(&newEntry->type, sizeof(int), 1, fp);
fread(&newEntry->creation, sizeof(int), 1, fp);
fread(&newEntry->index, sizeof(int), 1, fp);
directoryTable[i] = *newEntry;
}
It should be noted that the values of clusterSize and root are also read in using similar methods. I've already checked and their values are accurate in both situations. Since I was able to read those in without a problem, I have no idea why I'm having such a big problem now. I feel my use of malloc is not quite right, I've never worked with it before.
Also, here is a definition of directoryTable if needed:
typedef struct{
char * name;
unsigned int index;
unsigned int size;
unsigned int type;
unsigned int creation;
} directoryEntry;
Thank you guys for you time and if you need me to clarify on anything I'd be happy to.
Upvotes: 1
Views: 1362
Reputation: 13508
I see a lot of little problems:
I am not sure if any of these are causing the problem you are seeing, which you don't actually specify by the way, but it may at least get you pointed in the right direction.
Upvotes: 2