我在为一个类的项目遇到问题。我会马上说,我不是要求我为我做的,我只想更详细地说明如何使用这些功能。看来我正确地使用它们是因为它可以处理16个元素,但是它会挂在fclose()或segfaults上。在malloc和realloc中使用fwrite()和fread()
以下是我正在处理的内容。这是一个FAT16文件系统:
directoryTable是结构的“数组”。
void writeDirectory(int FATTable[], directoryEntry* directoryTable)
{
int currentCluster = 1;
directoryEntry* currentWrite = directoryTable;
FILE* theFile = fopen (fileSystemName, "rb+");
if(theFile != NULL)
{
cout << fseek (theFile, (clusterSize * currentCluster), SEEK_SET) << endl;
cout << fwrite(currentWrite, clusterSize, 1, theFile) << endl ;
while(FATTable[currentCluster] != 0xFFFF)
{
currentWrite = currentWrite + numberOfEntries;
currentCluster = FATTable[currentCluster];
cout << fseek (theFile, (clusterSize * currentCluster), SEEK_SET) << endl;
cout << fwrite(currentWrite, clusterSize, 1, theFile) << endl;
}
fflush(theFile);
cout << "Closing.." << errno << endl;
fclose(theFile);
}
else
cout << "FILE COULDN'T OPEN." << endl;
//Clean up that pointer
free(directoryTable);
}
基本上是一个指针(currentWrite)开始于另一个指针(directoryTable)的开始和以一次的文件的部分写入字节之一的clusterSize。如果还有剩余的数组/指针(directoryTable),它将递增当前写入的clusterSize字节并再次写入。
然后,它会读取和建立使用该阵列/指针:
directoryEntry* readDirectory(int FATTable[])
{
int currentCluster = directoryIndex;
//Allocate a clusterSize of memory
directoryEntry* directoryTable;
directoryTable = (directoryEntry*) malloc(clusterSize);
if(directoryTable == NULL)
cout << "!!! ERROR: Not enough memory!" << endl;
//A pointer to a part of that array
directoryEntry* currentRead = directoryTable;
numberOfDirTables = 1;
FILE* theFile = fopen (fileSystemName, "rb+");
if(theFile != NULL)
{
//Seek to a particular cluster in the file (
cout << fseek (theFile, (clusterSize * currentCluster), SEEK_SET) << endl;
cout << fread(currentRead, clusterSize, 1, theFile) << endl;
while(FATTable[currentCluster] != 0xFFFF)
{
numberOfDirTables++;
currentCluster = FATTable[currentCluster];
directoryTable = (directoryEntry*) realloc(directoryTable, (clusterSize*numberOfDirTables));
if(directoryTable == NULL)
cout << "!!! ERROR: Not enough memory!" << endl;
currentRead = currentRead + numberOfEntries;
cout << fseek (theFile, (clusterSize * currentCluster), SEEK_SET) << endl;
cout << fread(currentRead, clusterSize, 1, theFile) << endl;
}
cout << "Closing..." << errno << endl;
fclose(theFile);
cout << "Closed." << endl;
}
else
cout << "FILE COULDN'T OPEN." << endl;
return directoryTable;
}
基本上它会从第一簇读取并将它放入一个数组。然后它将增加currentRead clusterSize字节量并从另一个集群中读取。但它realloc的第一个,因此数组扩展了另一个clusterSize字节。
所以我的问题是,我是否正确使用fwrite,fread,malloc和realloc?它会出现,因为它的工作起来直到某一点。但我在C++中不太强大,所以我想我错过了一件引起重大内存问题的小事。
另外,我应该使用calloc来代替,因为我正在构建一个结构数组?
2012-02-18
Mike S