我在爲一個類的項目遇到問題。我會馬上說,我不是要求我爲我做的,我只想更詳細地說明如何使用這些功能。看來我正確地使用它們是因爲它可以處理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來代替,因爲我正在構建一個結構數組?
該死的,我以爲是問題所在。但是,不,我只是在重新分配之前和之後在directoryTable指針上運行一個cout,它們是相同的。要回答你的問題,它仍然引用了malloc'd的原始目錄表。 – 2012-02-18 23:00:33
那麼如果那不是「那個」問題那麼它仍然是問題之一。 =) – 2012-02-18 23:06:47
它應該被賦予一個新的內存地址?這會打破它嗎? – 2012-02-18 23:12:38