gpt4 book ai didi

c - 使用 fopen() 读取文件无法正常工作

转载 作者:行者123 更新时间:2023-11-30 17:09:22 25 4
gpt4 key购买 nike

我是 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 the file does not open

不是测试文件是否打开的正确方法。如果 fopen 无法打开文件,它将返回 NULL,这是您必须检查的内容。

if (fp == NULL) //If the file does not open

按照您的方式,NULL 值将通过您的检查,而“负”文件指针可能有效,但无法通过您的检查。尽管您提到了一个特定的文件内容,但您也提到了"file",我怀疑您的意思是说有些文件名有效,有些则无效:而不是一个有时会产生乱码的文件。

关于c - 使用 fopen() 读取文件无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com