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.
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.
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:
readlink /proc/self/exe
or you could use boost fs::path
and fs::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:
fstream * fs = new fstream("~/config_file");
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.
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()
, launch find
, 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 the fstream
object to write to or append to that file.
So for instance, this could look something like:
#include <limits.h>
#include <fstream>
#include <stdio.h>
char buffer[PATH_MAX];
//search the entire file-system starting from the root for "my_specific_file.txt"
FILE* located_file_handle = popen("find / -name my_specific_file.txt -print", "r");
//get the first file returned from the find operation and close the pipe
fgets(buffer, PATH_MAX, located_file_handle);
pclose(located_file_handle);
fstream file(buffer);
If you think there will be more than one file returned from the call to find
, then you should cycle though each of them using fgets
until you locate the one you want.
精彩评论