由于C它不是我习惯编程的语言,我不知道该怎么做.
我有一个项目文件夹,其中包含所有.c和.h文件以及一个conf文件夹,其中有一个config.txt文件可供阅读.我怎么能打开它?
FILE* fp = fopen("/conf/config.txt", "r");
if (fp != NULL)
{
//do stuff
}
else
printf("couldn't open file\n");
Run Code Online (Sandbox Code Playgroud)
我一直收到错误消息.为什么?
顺便说一句,这只需要在Windows上工作,而不是linux.
谢谢.
简单的方法是使用绝对路径......
my_file = fopen("/path/to/my/file.txt", "r");
Run Code Online (Sandbox Code Playgroud)
或者您可以使用相对路径.如果你的可执行文件在,/home/me/bin并且你的txt文件在/home/me/doc,那么你的相对路径可能是这样的
my_file = fopen("../doc/my_file.txt", "r");
Run Code Online (Sandbox Code Playgroud)
在相对路径中要记住的重要一点是,在运行可执行文件时,它与当前工作目录相关.因此,如果你使用了上面的相对路径,但是你在你的/tmp目录中并且你运行了/home/me/bin/myprog,它会尝试打开/tmp/../doc/my_file.txt(或/doc/my_file.txt)可能不存在的路径.
更健壮的选项是将文件的路径作为程序的参数,并将其作为第一个参数传递给fopen.最简单的例子就是使用argv[1]from main的参数,即
int main(int argc, char **argv)
{
FILE *my_file = fopen(argv[1], "r");
/* ... */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当然,您需要进行错误检查以验证argc> 2等.