gpt4 book ai didi

C fopen() - 绝对路径可能存在的问题

转载 作者:可可西里 更新时间:2023-11-01 11:26:14 24 4
gpt4 key购买 nike

<分区>

我目前在 Windows 10 下使用 Code::Blocks 13.12(编译器:GNU GCC)。

我正在尝试打开文件并加载其内容,但 fopen 给我带来了麻烦。 'input.txt' 与我的可执行文件位于同一目录中。我已经检查了权限。

获取路径的函数:

char* getFileName()                        
{
char *fileName; /* the path of the .txt file */
char path[MAX_PATH];

/* get the path of the executable */
GetModuleFileName(NULL, path, MAX_PATH);
/* remove the name of the executable from the path */
PathRemoveFileSpec(path);
/* check case where path is directory root */
if(PathIsRoot(path))
strcat(path, "\\*");

/* add the name of the .txt file to the path */
strcat(path, "\\input.txt");
/* not sure if needed */
path[strlen(path)] = '\0';
fileName = strdup((char *) path);

return fileName;
}

加载文件内容的函数:

bool loadDict(char *fileName)
{
FILE *fp; /* file stream */
char line[LINE_SIZE]; /* each line of the file */
// other variables

/* try to open file for reading */
if((fp = fopen(fileName, "r")) == NULL)
{
fprintf(stderr, "Error: Could not open the file '%s' to read\n", fileName);
return false;
}

// stuff done

/* file is no longer needed, close it */
if(fclose(fp))
{
fprintf(stderr, "Error: Could not close the file '%s' to read\n", fileName);
return false;
}
return true; /* in case no problem has occured */
}

主要内容:

int main()
{
char *fileName;

fileName = getFileName();
/* try to load the dictionary into memory */
if(!loadDict(fileName))
{
fprintf(stderr, "Error: The dictionary could be not loaded into memory.\nProgram terminating...\n");
return 1;
}

// other stuff
return 0;
}

我遇到了两个错误(无法打开文件,无法加载)。我已经尝试用“/”替换“\”或使用双斜杠,但均未成功。

 FILE *fp = fopen("path\\input.txt", "r");

如有任何帮助,我们将不胜感激。

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