【发布时间】:2015-10-24 20:45:48
【问题描述】:
我是 C 新手,正在学习如何读写文件以完成作业。有人可以向我解释为什么下面的函数有时会正确读取文件,有时会出现乱码吗?我相信它与文件名有关。但是,我打印出文件名并且它包含正确的字符串,所以我不知道为什么它有时会起作用而有时却不起作用(大多数时候它不起作用)。
更新:正确测试文件是否打开并从头开始构建路径名以确保我传递字符串文字的代码。输出有时正确有时无意义
void playGame(struct Room *HoldRooms[], char dirName[], char fileName[], int
roomStart)
{
//file and path name
char filePathName[100];
char tempString[100];
char string[MAX_STRING_LENGTH];
char field1[MAX_STRING_LENGTH];
char field2[MAX_STRING_LENGTH];
char field3[MAX_STRING_LENGTH];
filePathName[0] = 0;
char c;
strcpy(filePathName, dirName);
strcat(filePathName, "/");
strcat(filePathName, "room");
sprintf(tempString, "%d",roomStart);
strcat(filePathName,tempString);
//All lines contain three fields we will only need the third
FILE *fp = fopen(filePathName, "r");
chmod(filePathName, S_IRUSR | S_IRGRP | S_IROTH);
printf("The file is %s \n", filePathName);
if (fp == NULL) //If the file does not open
{
//fprintf(stderr, "Could not open %s\n", fileName);
//perror("in main");
printf("Could not open file\n" );
exit(1);
}
else
{
printf("Opened file %s \n", filePathName);
//fprintf(fp, "BLAH BLAH BLAH!");
fscanf(fp, "%s %s %s", field1, field2, field3);
printf("1: %s 2: %s 3: %s", field1, field2, field3);
}
fclose(fp); //close the file
}
【问题讨论】:
-
if (fp < 0)更改为if (fp == NULL)虽然这可能是完整的解决方案。阅读fopen的手册页。 -
文件是否包含您要读取的格式,即“string string string”
-
是的,它只是一个测试文件,上面写着 ROOM NAME: Cockpit