在C中具有动态位置的fopen()函数 [英] fopen() function with a dynamic location in C

查看:108
本文介绍了在C中具有动态位置的fopen()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想学习如何从动态位置使用fopen()函数打开文件.我的意思是,例如,它将是系统文件,而在另一台计算机中,此文件可以位于其他位置.因此,如果我不会动态地在代码中设置位置,则我的程序将无法在另一台计算机上运行.那么如何为我的程序动态设置位置,无论它在哪里都可以找到该文件?

I just want to learn that how can I open a file with fopen() function from a dynamic location. I mean, for example it will be a system file and in another computer, this file can be in another location. So if I will set my location in my code not dynamically, my program will not work in another computer. So how Can I set the location dynamically for my program will find this file wherever it is?

推荐答案

您可以(通常应该)通过常规的int argc, char**argv main. com/a/8324180/841108>您的main的形式参数.另请参见.

You can (and often should) pass program arguments to your main, thru the conventional int argc, char**argv formal arguments of your main. See also this.

(我专注于Linux,但是您可以将我的回答适应其他操作系统和平台)

因此,您将使用一些惯例来传递该文件路径(不是位置,该词通常是指程序的内存地址) (通常通过命令行启动程序).另请参见此答案.

So you would use some convention to pass that file path (not a location, that word usually refers to memory addresses) to your program (often thru the command line starting your program). See also this answer.

您可以(至少在Linux上)使用 getopt_long(3) 解析程序参数.但是有其他方式,您可以进行处理main的参数.

You could use (at least on Linux) getopt_long(3) to parse program arguments. But there are other ways, and you can process the arguments of main explicitly.

您还可以使用一些环境变量来传递该信息.您将使用 getenv(3)进行查询.另请阅读 environ(7).

You could also use some environment variable to pass that information. You'll query it with getenv(3). Read also environ(7).

许多程序都有 配置文件 s (其路径为连接到程序中,但通常可以由程序参数或环境变量给出),并且解析他们找到相关的文件路径.

Many programs have configuration files (whose path is wired into the program but often can be given by program arguments or by environment variables) and are parsing them to find relevant file paths.

您甚至可以考虑使用其他进程间通信来传递文件程序的路径.毕竟,文件路径只是一个字符串(具有 path_resolution(7)).有很多方法可以将一些数据传递给程序.

And you could even consider some other inter-process communication to pass a file path to your program. After all, a file path is just some string (with restrictions and interpretations explained in path_resolution(7)). There are many ways to pass some data to a program.

还请阅读有关通俗的信息,尤其是外壳正在扩展程序参数.您可能要使用 glob(3)之类的功能,或者 wordexp(3)在其他地方(例如某些地方)获得配置文件)进行类似的扩展.

Read also about globbing, notably glob(7). On Unix, the shell is expanding the program arguments. You may want to use functions like glob(3) or wordexp(3) on something obtained elsewhere (e.g. in some configuration file) to get similar expansion.

BTW,请确保在使用fopen时检查其是否失败.您可能会像此处那样使用perror.

BTW, be sure, when using fopen, to check against its failure. You'll probably use perror like here.

还要查看几个免费软件项目的源代码(也许在 github )以获得灵感.

Look also into the source code of several free software projects (perhaps on github) for inspiration.

这篇关于在C中具有动态位置的fopen()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆