我正在编写一个文本游戏,其中将用户输入与我拥有的文本文件中可用的命令列表进行比较。
它工作正常,但我希望它循环播放,以便用户在输入打破循环并继续执行程序的命令之前可以执行多个操作。不幸的是,我的文件指针在循环的第二次迭代中变成NULL
,因此完全脱离了程序。
缩进有点令人困惑,对此我深表歉意:
int mansionOutside(void)
{
int stop = 1; //control variable for while, yeah I know its a shit method of doing it, sue me
char choice[25]; //Variable to store user input
char word_match[15] = "outside"; //counter and .txt will be strcat to it
char text_line[73]; //size of line for txt files
char line1[25]; //takes current line being read from file
char temp[2]; //character and '\0' so counter can be made into a string and strcat into word_match
int counter = 1; //counts number of lines
int stop2 = 1;
while (stop2 == 1)
{
FILE *fptr;
fptr = fopen("mansion_commands.txt", "r"); //opens file
int lookdoor_counter = 0;
printf("%p\n", fptr);
if (fptr == NULL)
{
perror("ERROR!"); //Error handling for not opening file
exit(EXIT_FAILURE);
}
else
{
while (stop == 1)
{
puts(""); //newline, as the previous function ends in a text line
fgets(choice, sizeof choice, stdin); //store input in choice with buffer overflow protection
while (fgets(line1, 25, fptr) != NULL) //reads until newline
{
if (strcmp(line1, choice) == 0) //if choice is equal to the current line
{
//printf("%s\n", line1); //debugging print
if (strcmp(line1, "LOOK door") == 0)
{
lookdoor_counter++; //so that on entering LOOK door a second time, a different
//message will appear
}
stop = 0; // will exit from loop
break; //break ensures we can use the current counter value for later
}
else
{
counter++;
//printf("%s + %s\n", line1, choice); //debugging
}
}
if (stop == 1)
{
printf("I dont understand\n");
//printf("%d\n", counter);
//printf("%s\n", line1);
//printf("%s\n", choice);
counter = 1; //counter is reset to be able to try again
rewind(fptr);
}
}
fclose(fptr);
if (lookdoor_counter == 2)
{
counter += 1;
}
counter = counter + '0'; //convert counter digit to its equivalent ascii
temp[0] = counter;
temp[1] = '\0'; //temp becomes a string with counter and EOF char
//printf("%c\n", counter);
strncat(word_match, temp , 1); //wordmatch gets counter strncat to it
strcat(word_match, ".txt"); /*If the string is found on the second line
word_match will be (outside2.txt), which contains the appropriate
message for that user command*/
//printf("%s\n", word_match); //debugging
if (strcmp(word_match, "outside4.txt") == 0)
{
stop2 = 0;
}
fptr = fopen(word_match, "r"); //we open word_match file
if (fptr == NULL)
{
printf("ERROR!\n"); //error handling
exit(EXIT_FAILURE);
}
else
{
//printf("Debugging : File opened Successfully\n");
while (fgets (text_line, 72, fptr) != NULL)
{
printf("%s", text_line); // Prints every Line with a 2 sec delay
//delay(2);
}
}
}
fclose(fptr);
}
return 1;
}
答案 0 :(得分:2)
fptr = fopen("mansion_commands.txt", "r"); //opens file
if (!fptr)perror("fopen");
添加此if条件,然后查找实际错误是什么。也许您对fs没有权限,或者路径不正确,等等。