通过C编码读取和显示文本文件的内容
我正试图用C语言编写一个关于种族选择的游戏。 每个种族都有自己的“故事”,当用户选择阅读其中一个故事时, 我想发生的是 当程序在命令提示符下运行时,它将显示我在特定文本文件中键入的有关所选种族故事的内容 这就是我到目前为止所做的通过C编码读取和显示文本文件的内容,c,text,fgetc,C,Text,Fgetc,我正试图用C语言编写一个关于种族选择的游戏。 每个种族都有自己的“故事”,当用户选择阅读其中一个故事时, 我想发生的是 当程序在命令提示符下运行时,它将显示我在特定文本文件中键入的有关所选种族故事的内容 这就是我到目前为止所做的 void Race(char nameRace[20]) { int race_choice,race_choice2,race_story; FILE *race; FILE *race1; FILE *race2;
void Race(char nameRace[20])
{
int race_choice,race_choice2,race_story;
FILE *race;
FILE *race1;
FILE *race2;
FILE *race3;
printf("The Races: 1.Human 2.Elf 3.Orc\n");
printf("Press 1 for Details of Each Races or 2 for selection: ");
scanf("%d",&race_choice);
if (race_choice==1)
{
printf("Which Race do you wish to know about?\n\t1.The Human\n\t2.The Elf\n\t3.The Orc\n\t: ");
scanf("%d",&race_story);
if (race_story==1)
{
race1=fopen("race1.txt","r");
fgetc(race1); // This does not display what I have typed on the race1.txt file on Command prompt.
// And I plan to write 2~3 paragraphs on the race1.txt file.
printf("\nGo Back to the Selection?(1 to Proceed)\n ");
scanf("%d",&race_choice2);
if (race_choice2==1)
{
printf("\n\n");
Race(nameRace);
}
else
{
wrongInput(race_choice2);// This is part of the entire code I have created. This works perfectly.
}
}
}
}
请帮帮我?:)求你了 您似乎缺少的功能是读取文本文件并将其输出的能力。因此,编写一个函数来完成这项工作可能是一个好主意,然后,无论何时需要显示文件内容,都可以将文件名传递给我们的函数,让它完成工作,例如
static void display_file(const char *file_name)
{
FILE *f = fopen(file_name, "r"); // open the specified file
if (f != NULL)
{
INT c;
while ((c = fgetc(f)) != EOF) // read character from file until EOF
{
putchar(c); // output character
}
fclose(f);
}
}
然后在你的代码中把它叫做
display_file("orcs.txt");
fgetc函数读取并返回文件中的单个字符,但不打印它。 因此,您需要执行以下操作:
while(!feof(race1)) { // Following code will be executed until end of file is reached
char c = fgetc(race1); // Get char from file
printf("%c",c); // Print it
}
它将逐字符打印
race1
的内容。我认为您可能希望逐行读取文件,因此最好使用fgets()
而不是fgetc()
例如:
while(!feof(race1)) // checks to see if end of file has been reached for race1
{
char line[255]; // temporarily store line from text file here
fgets(line,255,race1); // get string from race1 and store it in line, max 255 chars
printf("%s",line); // print the line from the text file to the screen.
}
如果用上面的代码块替换fgetc(race1)
,它可能会工作。我没有试过运行它,但它应该可以工作