xcode 不使用完整路径的c语言同一目录下的fopen文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13822342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:17:35  来源:igfitidea点击:

fopen file from same directory in c language without using the full path

cxcodefiledirectoryfopen

提问by user1883003

I'm trying to do the following:

我正在尝试执行以下操作:

FILE *fileNAME = fopen("file.txt", "r");

It works when I have:

当我有:

FILE *fileNAME = fopen("users/username/desktop/folder/file.txt", "r");

but as I want to use this file outside my home computer the path should be relative, especially for an end user who has no access to the actual source code. My question is, how to actually make this work and if the issue is due to the compiler not using the right directory by default, how do I change that? (I am using XCODE)

但是因为我想在我的家用计算机之外使用这个文件,路径应该是相对的,特别是对于无法访问实际源代码的最终用户。我的问题是,如何实际进行这项工作,如果问题是由于编译器默认没有使用正确的目录,我该如何更改?(我正在使用 XCODE)

回答by MOHAMED

you can pass the file path as input argument when you call your program via command

当您通过命令调用程序时,您可以将文件路径作为输入参数传递

$myprogram users/username/desktop/folder/file.txt

and in your code source you can get this path from argv

在您的代码源中,您可以从 argv 获取此路径

int main (int argc, char **argv)
{
   char *file_path = argv[1];
   ....
} 

The argc is the length of the argv array. so if the array length is lower than 2 than your program should return help message to indicate to the user to input the file path as argument

argc 是 argv 数组的长度。因此,如果数组长度小于 2,则您的程序应返回帮助消息以指示用户输入文件路径作为参数

int main (int argc, char **argv)
{
   char *file_path;
   if (argc <2) {
      printf("Usage: %s <file path>\n", argv[0]);
      exit(1);
   }
   file_path = argv[1];
   ....
} 

回答by Nemanja Boric

If you are using Mac OS X (Xcode, right, I am not OS X user, but I assume this is it?), you can get current executable path (not the current working directory path) with

如果您使用的是 Mac OS X(Xcode,对,我不是 OS X 用户,但我认为是这样?),您可以获得当前的可执行路径(不是当前的工作目录路径)

char path[1024];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0)
    printf("executable path is %s\n", path);
else
    printf("buffer too small; need size %u\n", size);

After this, you have two ways:

在此之后,您有两种方法:

1) Either update combine file paths with exe directory (like sprintf(filepath, "%s/%s", path, "file.txt");)

1)要么更新组合文件路径与exe目录(如sprintf(filepath, "%s/%s", path, "file.txt");

2) Change current directory with chdirfunction and access files with relative path.

2) 使用chdir函数更改当前目录并使用相对路径访问文件。

Edit: _NSGetExecutablePath returns executable path, not executable directory, so use substr/strrchrto extract path prior to the last occurence of '/' character.

编辑:_NSGetExecutablePath 返回可执行路径,而不是可执行目录,因此使用substr/strrchr在最后一次出现 '/' 字符之前提取路径。