我试图在学习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