我試圖在學習C的同時重新學習C,而我在它的時候(我在大學學到了它,但沒有最近用它做了很多)。我正在寫一個chip8仿真器,但我在將遊戲加載到仿真器的內存時遇到了問題。問題在我看來,我沒有正確使用fopen(),並且我正在嘗試創建的文件流沒有找到該文件,或者我只是在執行中做了不正確的事情。C - 讀取文件並將內容寫入數組一個字符一次char
void loadGame(char* name) {
//Use fopen to read the program into memory, this loop will use the stream
FILE* game = fopen(name, "r"); //Open the game file as a stream.
unsigned int maxGameSize = 3584; //The max game size available 0x200 - 0xFFF
char gameBuffer[maxGameSize]; //The buffer that the game will be temporarily loaded into.
if (game == NULL) { //THIS IS WHERE THE ERROR HAPPENS. game does == NULL
fprintf(stderr, "The game either can't be opened or doesn't exist!\n");
exit(1);
} else {
while (!feof(game)) {
if (fgets(gameBuffer, maxGameSize, game) == NULL) { //load the file into the buffer.
break; //Reached the EOF
}
}
//Now load the game into the memory.
int counter = 0;
while (counter < maxGameSize) {
memory[counter+512] = gameBuffer[counter];
counter++;
}
}
fclose(game);
}
我在所有的首都發表了一個評論,我的邏輯錯誤發生了,所以它會脫穎而出。
這是我的主要方法,供參考。而且我的編譯代碼在同一個目錄下有一個pong。
int main(int argc, char **argv) {
setupGraphics(); //A stub for now
setupInput(); //Another stub for now.
initialize(); //Yet another stub.
loadGame("PONG");
}
我很欣賞任何人可能有的見解!讓我知道是否應該在任何地方添加或更具描述性。
編輯:
我想我使用了MrZebra的信息!我想發佈我的答案,我相信這是我想要的。這是我的新的loadGame()方法。
void loadGame(char* name) {
unsigned int maxGameSize = 3584; //This is how many 8-bit cells is available in the memory.
char gameBuffer[maxGameSize]; //Temporary buffer to read game into from file.
FILE* game = fopen(name, "rb");
if (game == NULL) {
perror("Failed to open game.\n");
} else {
printf("Game found.\n");
}
fread(gameBuffer, sizeof(char), maxGameSize, game); //Read file into temp buffer
fclose(game);
//Now load the game into the memory.
int counter = 0;
while (counter < maxGameSize) {
memory[counter+512] = gameBuffer[counter];
counter++;
}
}
確保您已閱讀了'name'文件權限和路徑'名稱「確實存在。你也可以使用'errno'(通過包含適當的頭文件)並打印'errno'來查看實際出錯的地方。 – mtahmed
1)函數loadGame()裏的'name'是什麼意思? 2)不要使用'feof()'。只要測試你使用的任何閱讀功能的結果。 – chux