简体   繁体   English

在C linux中打开文件

[英]Open file in C linux

I am using C to open a file for reading. 我正在使用C打开文件进行读取。 I have this code : 我有这个代码:

fp = fopen("./settings.cfg","r");
if (fp != NULL)
    printf("OK");
else
    printf("ERROR");

but I always get an error. 但我总是会出错。

The file is located in the folder where the executable resides. 该文件位于可执行文件所在的文件夹中。 I have tried writing only "settings.cfg". 我尝试只写“ settings.cfg”。 What might be the problem? 可能是什么问题?

Try perror() to have the library itself tell you what, if anything, is wrong. 尝试使用perror()让库本身告诉您什么(如果有的话)是错误的。

fp = fopen("./settings.cfg", "r");
if (fp != NULL)
    printf("OK\n");
else perror("fopen");

You are opening the file in the "current directory", not "in the folder where the executable is". 您正在“当前目录”中而不是“在可执行文件所在的文件夹中”打开文件。

In fact, unix has no easy way to find that particular folder; 实际上,Unix没有找到该特定文件夹的简便方法。 in Linux you could readlink() the /proc/[your pid]/exe link to find the executable and strip off the filename portion -- that will work in many cases, but there are some fringe cases like hardlinks that will make it fail. 在Linux中,您可以readlink()/ proc / [您的pid] / exe链接以找到可执行文件并剥离文件名部分-在许多情况下都可以使用,但是在某些情况下,例如硬链接会使它失败。

From which directory do you run the program? 您从哪个目录运行程序? It won't have the directory where it resides as the current directory, it will be inherited from the environment. 它没有当前目录所在的目录,它将从环境中继承。

Could also be rights, that the file is owned by someone else and you don't have read rights. 也可以是权利,该文件归他人所有,而您没有读取权限。

Also double-check the filename. 还要仔细检查文件名。 This sounds obvious, but do it anyway. 这听起来很明显,但是还是要这样做。

If file you are trying to open is in the same directory of your C compiled file, you must simply do 如果您要打开的文件位于C编译文件的同一目录中,则只需执行

fp = fopen("settings.cfg","r");
if (fp != NULL)
  printf("OK");
else
  printf("ERROR");

without the initial " ./ " at the file's name 文件名不带首字母“ ./”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM