如何使用 fstream 写入 C 中可执行文件目录上方的文件?
我正在尝试写入不在可执行文件所在目录中的文件;我也希望它能够工作,无论可执行文件在哪里(我相信这会排除使用“..”)。我需要这个才能在 Linux 上工作。谢谢。
I'm trying to write to a file that is not in the directory that the executable is in; I also want it to work no matter where the executable is (I believe that would rule out using ".."). I need this to work on Linux. Thank-you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
已经有人询问过这个问题,请参阅获取可执行文件的路径或在没有 /proc/self/exe 的情况下查找当前可执行文件的路径以获得一个好的答案,或者自己搜索。
您的问题归结为获取正在运行的可执行文件的绝对路径。
This has been asked already, see Get path of executable or Finding current executable's path without /proc/self/exe for a good answer, or search yourself.
Your problem boils down to getting the absolute path to the running executable.
相对路径通常从运行目录开始解析,该目录不一定是可执行文件目录(而是启动可执行文件的 shell 中的当前目录)。
在 Linux 下,您可以使用以下命令读取可执行文件的目录:
或者您可以使用 boost
fs::path
和fs::system_complete
。然后,您必须从该字符串中删除最后一个组件,即可执行文件名称。获得可执行目录的路径后,在其后面附加“/..”,您将获得可执行目录上方的目录。
A relative path is usually resolved starting from the running directory, which is not necessarily the executable directory (rather the current directory in the shell from which the executable is launched).
Under linux, you can read the directory of the executable with:
or you could use boost
fs::path
andfs::system_complete
. Then you have to remove from that string the last component, which is the executable name.Once you have the path of the executable directory, append "/.." to it and you will get the directory above the executable directory.
如果您提前知道,则可以使用绝对路径:
如果文件有所不同,您可以从用户输入或配置文件中获取路径。
根据文件所在位置、文件是否移动以及程序所在位置,您实际上可以使用相对路径。从你提供的信息来看,我无法判断。
You can use an absolute path, if you know it ahead of time:
If the file varies, you can take the path from user input or a configuration file.
Depending on where the file is, whether it moves and where the program is, you may actually be able to use a relative path. From the info you've given, I couldn't tell.
您可以轻松地做到这一点,但您必须拥有要处理的文件的绝对路径,或者必须在可执行文件和要访问的文件之间创建一些相对文件结构。
另一种选择是,您可以使用分叉进程或 popen() 启动 find 并为其提供适当的参数来定位您要处理的文档,然后然后使用返回的字符串作为参数来创建 fstream 对象以写入或附加到该文件。
例如,这可能看起来像这样:
如果您认为调用
find
会返回多个文件,那么您应该使用fgets
循环遍历每个文件> 直到找到您想要的那个。You can do this easily, but you will have to have an absolute path to the file you want to work on, or you will have to create some relative file-structure between your executable and the file you are wanting to access.
Another option is you could, using a forked process or
popen()
, launchfind
, and give it the appropriate arguments to locate the document you are wanting to work on, and then use that returned string as the argument to create thefstream
object to write to or append to that file.So for instance, this could look something like:
If you think there will be more than one file returned from the call to
find
, then you should cycle though each of them usingfgets
until you locate the one you want.