Get full path of executable of running process on HPUX - c++

I want to get the full path of the running process (executable) without having root permission using C++ code. Can someone suggest a way to achieve this.
on Linux platforms i can do it by using following way.
char exepath[1024] = {0};
char procid[1024] = {0};
char exelink[1024] = {0};
sprintf(procid, "%u", getpid());
strcpy(exelink, "/proc/");
strcat(exelink, procid);
strcat(exelink, "/exe");
readlink(exelink, exepath, sizeof(exepath));
Here exepath gives us the full path of the executable.
Similarly for windows we do it using
GetModuleFileName(NULL, exepath, sizeof(exepath)); /* get fullpath of the service */
Please help me how to do it on HP-UX since there is no /proc directory in HP-UX.

First, I'd like to comment on your Linux solution: it is about 5 times as long as it needs to be, and performs a lot of completely unnecessary operations, as well as using 1024 magic number which is just plain wrong:
$ grep PATH_MAX /usr/include/linux/limits.h
#define PATH_MAX 4096 /* # chars in a path name */
Here is a correct minimal replacement:
#include <limits.h>
...
char exepath[PATH_MAX] = {0};
readlink("/proc/self/exe", exepath, sizeof(exepath));
Second, on HP-UX you can use shl_get_r() to obtain information about all loaded modules. At index 0, you will find information about the main executable. The desc.filename will point to the name of the executable at execve(2) time.
Unfortunately, that name is relative, so you may have to search $PATH, and may fail if the application did putenv("PATH=some:new:path") or if the original exename was e.g. ./a.out and the application has performed chdir(2) since.

On HP-UX, use pstat:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#define _PSTAT64
#include <sys/pstat.h>
int main(int argc, char *argv[])
{
char filename[PATH_MAX];
struct pst_status s;
if (pstat_getproc(&s,sizeof(s),0,getpid()) == -1) {
perror("pstat_getproc");
return EXIT_FAILURE;
}
if (pstat_getpathname(filename,sizeof(filename),&s.pst_fid_text) == -1) {
perror("pstat_getpathname");
return EXIT_FAILURE;
}
printf("filename: %s\n",filename);
return EXIT_SUCCESS;
}

The earlier answer referring to the Unix Programming FAQ was right. The problem, even with the Linux /proc answer, is that the path to the executable may have changed since the exec(). In fact, the executable may have been deleted. Further complications arise from considering links (both symbolic and hard) -- there may be multiple paths to the same executable. There is no general answer that covers all cases, since there may not be a path remaining, and if there is one it may not be unique.
That said, using argv[0] with some logic, as advocated by cjhuitt earlier, will probably do what you want 99.9% of the time. I'd add a check for a path containing "/" before doing the relative path check (and note, you must do that before any cwd() calls). Note that if your calling program is feeling mischievous, there's a host of things that can be done between fork() and exec() to mess this up. Don't rely on this for anything that could affect application security (like location of configuration files).

For what purpose do you need the executable path? Bear in mind, as I put in my earlier post, that there is no guarantee that a path to the executable will exist, or that it will be unique.

I have done this before in a general case. The general idea is to grab argv[0], and do some processing on it:
int main( int argc, char** argv )
{
string full_prog_path = argv[0];
if ( full_prog_path[0] == "/" )
{ // It was specified absolutely; no processing necessary.
}
else
{
string check_cwd = getcwd();
check_cwd += argv[0];
if ( FileExists( check_cwd ) )
{ // It was specified relatively.
full_prog_path = check_cwd;
}
else
{ // Check through the path to find it
string path = getenv( "PATH" );
list<string> paths = path.split( ":" );
foreach( test_path, paths )
{
if ( FileExists( test_path + argv[0] ) )
{ // We found the first path entry with the program
full_prog_path = test_path + argv[0];
break;
}
}
}
}
cout << "Program path: " << full_prog_path << endl;
return 0;
}
Obviously, this has some assumptions that might break at some point, but it should work for most cases.

Related

Extracting the immediate parent directory from a file path using boost

Assuming I have
String t = "c:/foo/foo1/foo2/foo3/file.txt"
I want to extract "foo3/file.txt".
How can I do this (using boost or std)?
Here is what I've been trying to so far:
boost::filesystem::path pathToObject(t);
Using pathToObject.filename() I can extract the file name of course. And I've played around with t.find_last_of("/") but I really need like t.find_second_to_last_of("/").
string::find_last_of has an optional argument which lets you specify how far into the string you are looking.
So you can define
size_t second_to_last = t.find_last_of("/", t.find_last_of("/")-1);
std::string file_with_parent = t.substr(second_to_last+1);
The second argument tells him to only search before the last /.
WARNING: This might differ from what you want if you have stuff like "C:/bli/bla//blubb.txt". In general, paths can be complex and confusing and trying to conquer them with string manipulation will only work for very well-behaved input, which one usually can't assume.
I therefore recommended using a proper tool for this job.* But since the question claimed that find_last_of wouldn't do the job I felt quite compelled to remind people that the standard facilities are not entirely as impotent as many seem to believe them to be.
*I suspect the boost path lib to be one but I have never worked with it.
It is rather odd to extract a path like that. Maybe you are looking for a relative path? boost filesystem has a tool for that. Be sure to give the documentation a good look over. But to answer your question:
namespace bfs= boost::filesystem;
int main( ) {
bfs::path path( "c:/foo/foo1/foo2/foo3/file.txt" );
bfs::path target( path );
target.remove_filename( );
target= target.filename( ) / path.filename( );
std::cout << target << std::endl;
}
I don't have a compiler handy to test it, but based on the example here, this code should basically work or point you in about the right direction. It could probably be simplified a little bit even from what I've written here.
path p1( "c:/foo/foo1/foo2/foo3/file.txt" );
path p2;
for (path::iterator it(p1.end()), int i = 0; it != p1.begin() && i < 2; --it, ++i) {
path temp = p2;
p2 = it;
p2 /= temp;
}
Here is the solution I ended up using:
std::string t = pathObject.parent_path().filename().string();
t.append("/");
t.append(pathObject.filename().string());
Using parent_path gave me just the path. Then I used the filename to extract just the directory. Then I appended the filename of the child directory.
Following method return immediate parent directory.
#include <string>
string getParentDirectory(string& filePath)
{
if (filePath.empty() == false)
{
size_t toPos = filePath.find_last_of('\\') - 1;
if (toPos != string::npos)
{
size_t fromPos = filePath.find_last_of('\\', toPos);
if (fromPos != string::npos)
{
return filePath.substr(fromPos + 1, toPos - fromPos);
}
}
}
return "";
}
int main()
{
string str = "D:\\Devs\\Test\\sprite.png";
string parentDir = getParentDirectory(str);
return 0;
}
It prints the value of parentDir is "Test".

finding out the path to a file at runtime

In a program I open a file say file.dat at runtime. The problem is when i run the executable it expects the file to be in the directory from where it is executed. I want the program to look into the same directory where the executable is present. What modifications should I make in my program (or in the build system).
For example consider this program:
int main()
{
std::ifstream ip("file.dat");
// do something.
return 0;
}
I am working on Ubuntu with g++-4.6 compiler and CMake build system. Since the project supports out-of-source build that means the program executable can be anywhere depending upon the directory where the cmake was invoked from.
Thanks for the help...
On many systems, the argv[0] parameter will have the path used to execute the program. Whether or not this is the full path of the program depends on how it was invoked.
int main (int argc, char *argv[]) {
std::string progname(argv[0]);
std::string datafile;
if (progname.find_last_of('/') != std::string::npos)
datafile = progname.substr(0, progname.find_last_of('/')+1);
datafile += "file.dat";
std::ifstream ip(datafile.c_str());
//...
}
On Linux reading /proc/self/exe is the best way to go.
char app_path[1024];
ssize_t len = ::readlink("/proc/self/exe", app_path, sizeof(app_path)-1);
if (len != -1) {
app_path[len] = '\0';
} else {
// handle error
}
For other OS, see: https://stackoverflow.com/a/1024937/105015

how to get system or user temp folder in unix and windows?

I am writing a C++ problem. It need to work on both Windows and Unix OS.
How to get user or system tmp folder on different OS?
Update: Thanks #RoiDanton, the most up to date answer is std::filesystem::temp_directory_path (C++17)
Try boost::filesystem's temp_directory_path() which internally uses:
ISO/IEC 9945 (POSIX): The path supplied by the first environment variable found in the list TMPDIR, TMP, TEMP, TEMPDIR. If none of these are found, "/tmp", or, if macro __ANDROID__ is defined, "/data/local/tmp"
Windows: The path reported by the Windows GetTempPath API function.
Interestingly, Window's GetTempPath uses similar logic to the POSIX version: the first environment variable in the list TMP, TEMP, USERPROFILE. If none of these are found, it returns the Windows directory.
The fact that these methods primarily rely on environment variables seems a bit yuck. But thats how it seems to be determined. Seeing as how mundane it really is, you could easily roll your own using cstdlib's getenv function, especially if you want specific order prioritization/requirements or dont want to use another library.
Use the $TMPDIR environment variable, according to POSIX.
char const *folder = getenv("TMPDIR");
if (folder == 0)
folder = "/tmp";
if you use QT(Core) you can try QString QDir::tempPath() , or use it's implementation in your code (QT is open, so, check how they do).
The doc say : On Unix/Linux systems this is usually /tmp; on Windows this is usually the path in the TEMP or TMP environment variable.
According to the docs, the max path is MAX_PATH (260). If the path happens to be 260, the code in the sample above (als plougy) will fail because 261 will be returned. Probably the buffer size should be MAX_PATH + 1.
TCHAR szPath[MAX_PATH + 1];
DWORD result = GetTempPath(MAX_PATH + 1, szPath);
if (result != ERROR_SUCCESS) {
// check GetLastError()
}
Handy function :
std::string getEnvVar( std::string const & key )
{
char * val = getenv( key.c_str() );
return val == NULL ? std::string("") : std::string(val);
}
I guess TEMP or something could be passed as an argument? Depending on the OS of course. getenv is part of stdlib so this should also be portable.
If you get an access to main() function code, may be better is to put necessary folder names through the main()'s **argv and use an OS-dependend batch launcher.
For example, for UNIX
bash a_launcher.sh
where a_launcher.sh is like
./a.out /tmp
On Windows: Use GetTempPath() to retrieve the path of the directory designated for temporary files.
wstring TempPath;
wchar_t wcharPath[MAX_PATH];
if (GetTempPathW(MAX_PATH, wcharPath))
TempPath = wcharPath;
None of these examples are really concrete and provide a working example (besides std::filesystem::temp_directory_path) rather they're referring you to microsoft's documentation, here's a working example using "GetTempPath()" (tested on windows 10):
//temp.cpp
#include <iostream>
#include <windows.h>
int main()
{
TCHAR path_buf[MAX_PATH];
DWORD ret_val = GetTempPath(MAX_PATH, path_buf);
if ( ret_val > MAX_PATH || (ret_val == 0) )
{
std::cout << "GetTempPath failed";
} else {
std::cout << path_buf;
}
}
outputs:
C:\>temp.exe
C:\Users\username\AppData\Local\Temp\

How do I find the current system timezone?

On Linux, I need to find the currently configured timezone as an Olson location. I want my (C or C++) code to be portable to as many Linux systems as possible.
For example. I live in London, so my current Olson location is "Europe/London". I'm not interested in timezone IDs like "BST", "EST" or whatever.
Debian and Ubuntu have a file /etc/timezone that contains this information, but I don't think I can rely on that file always being there, can I? Gnome has a function oobs_time_config_get_timezone() which also returns the right string, but I want my code to work on systems without Gnome.
So, what's the best general way to get the currently configured timezone as an Olson location, on Linux?
It's hard to get a reliable answer. Relying on things like /etc/timezone may be the best bet.
(The variable tzname and the tm_zone member of struct tm, as suggested in other answers, typically contains an abbreviation such as GMT/BST etc, rather than the Olson time string as requested in the question).
On Debian-based systems (including Ubuntu), /etc/timezone is a file containing the right answer.
On some Redhat-based systems (including at least some versions of CentOS, RHEL, Fedora), you can get the required information using readlink() on /etc/localtime, which is a symlink to (for example) /usr/share/zoneinfo/Europe/London.
OpenBSD seems to use the same scheme as RedHat.
However, there are some issues with the above approaches. The /usr/share/zoneinfo directory also contains files such as GMT and GB, so it's possible the user may configure the symlink to point there.
Also there's nothing to stop the user copying the right timezone file there instead of creating a symlink.
One possibility to get round this (which seems to work on Debian, RedHat and OpenBSD) is to compare the contents of the /etc/localtime file to the files under /usr/share/zoneinfo, and see which ones match:
eta:~% md5sum /etc/localtime
410c65079e6d14f4eedf50c19bd073f8 /etc/localtime
eta:~% find /usr/share/zoneinfo -type f | xargs md5sum | grep 410c65079e6d14f4eedf50c19bd073f8
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/London
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Belfast
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Guernsey
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Jersey
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Isle_of_Man
...
...
Of course the disadvantage is that this will tell you all timezones that are identical to the current one. (That means identical in the full sense - not just "currently at the same time", but also "always change their clocks on the same day as far as the system knows".)
Your best bet may be to combine the above methods: use /etc/timezone if it exists; otherwise try parsing /etc/localtime as a symlink; if that fails, search for matching timezone definition files; if that fails - give up and go home ;-)
(And I have no idea whether any of the above applies on AIX...)
I've been working on a free, open source C++11/14 library which addresses this question in a single line of code:
std::cout << date::current_zone()->name() << '\n';
It is meant to be portable across all recent flavors of Linux, macOS and Windows. For me this program outputs:
America/New_York
If you download this library, and it doesn't work you, bug reports are welcome.
There is no standard c or c++ function for this. However, GNU libc has an extention. its struct tm has two extra members:
long tm_gmtoff; /* Seconds east of UTC */
const char *tm_zone; /* Timezone abbreviation */
This means that if you use one of the functions which populates a struct tm (such as localtime or gmtime) you can use these extra fields. This is of course only if you are using GNU libc (and a sufficiently recent version of it).
Also many systems have a int gettimeofday(struct timeval *tv, struct timezone *tz); function (POSIX) which will fill in a struct timezone. This has the following fields:
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
Not exactly what you asked for, but close...
Pretty late in the day, but I was looking for something similar and found that ICU library has the provision to get the Olson timezone ID: http://userguide.icu-project.org/datetime/timezone
It is now installed on most linux distributions (install the libicu-dev package or equivalent). Code:
#include <unicode/timezone.h>
#include <iostream>
using namespace U_ICU_NAMESPACE;
int main() {
TimeZone* tz = TimeZone::createDefault();
UnicodeString us;
tz->getID(us);
std::string s;
us.toUTF8String(s);
std::cout << "Current timezone ID: " << s << '\n';
delete tz;
return 0;
}
And to get the abbreviated/POSIX timezone names (should also work on Windows):
#include <time.h>
int main() {
time_t ts = 0;
struct tm t;
char buf[16];
::localtime_r(&ts, &t);
::strftime(buf, sizeof(buf), "%z", &t);
std::cout << "Current timezone (POSIX): " << buf << std::endl;
::strftime(buf, sizeof(buf), "%Z", &t);
std::cout << "Current timezone: " << buf << std::endl;
I see two major linux cases:
Ubuntu. There should be a /etc/timezone file. This file should only contain the timezone and nothing else.
Red Hat. There should be a /etc/sysconfig/clock that contains something like: ZONE="America/Chicago"
In addition, Solaris should have an /etc/TIMEZONE file that contains a line like: TZ=US/Mountain
So based on the above, here is some straight C that I believe answers the OP's question. I have tested it on Ubuntu, CentOS (Red Hat), and Solaris (bonus).
#include <string.h>
#include <strings.h>
#include <stdio.h>
char *findDefaultTZ(char *tz, size_t tzSize);
char *getValue(char *filename, char *tag, char *value, size_t valueSize);
int main(int argc, char **argv)
{
char tz[128];
if (findDefaultTZ(tz, sizeof(tz)))
printf("Default timezone is %s.\n", tz);
else
printf("Unable to determine default timezone.\n");
return 0;
}
char *findDefaultTZ(char *tz, size_t tzSize)
{
char *ret = NULL;
/* If there is an /etc/timezone file, then we expect it to contain
* nothing except the timezone. */
FILE *fd = fopen("/etc/timezone", "r"); /* Ubuntu. */
if (fd)
{
char buffer[128];
/* There should only be one line, in this case. */
while (fgets(buffer, sizeof(buffer), fd))
{
char *lasts = buffer;
/* We don't want a line feed on the end. */
char *tag = strtok_r(lasts, " \t\n", &lasts);
/* Idiot check. */
if (tag && strlen(tag) > 0 && tag[0] != '#')
{
strncpy(tz, tag, tzSize);
ret = tz;
}
}
fclose(fd);
}
else if (getValue("/etc/sysconfig/clock", "ZONE", tz, tzSize)) /* Redhat. */
ret = tz;
else if (getValue("/etc/TIMEZONE", "TZ", tz, tzSize)) /* Solaris. */
ret = tz;
return ret;
}
/* Look for tag=someValue within filename. When found, return someValue
* in the provided value parameter up to valueSize in length. If someValue
* is enclosed in quotes, remove them. */
char *getValue(char *filename, char *tag, char *value, size_t valueSize)
{
char buffer[128], *lasts;
int foundTag = 0;
FILE *fd = fopen(filename, "r");
if (fd)
{
/* Process the file, line by line. */
while (fgets(buffer, sizeof(buffer), fd))
{
lasts = buffer;
/* Look for lines with tag=value. */
char *token = strtok_r(lasts, "=", &lasts);
/* Is this the tag we are looking for? */
if (token && !strcmp(token, tag))
{
/* Parse out the value. */
char *zone = strtok_r(lasts, " \t\n", &lasts);
/* If everything looks good, copy it to our return var. */
if (zone && strlen(zone) > 0)
{
int i = 0;
int j = 0;
char quote = 0x00;
/* Rather than just simple copy, remove quotes while we copy. */
for (i = 0; i < strlen(zone) && i < valueSize - 1; i++)
{
/* Start quote. */
if (quote == 0x00 && zone[i] == '"')
quote = zone[i];
/* End quote. */
else if (quote != 0x00 && quote == zone[i])
quote = 0x00;
/* Copy bytes. */
else
{
value[j] = zone[i];
j++;
}
}
value[j] = 0x00;
foundTag = 1;
}
break;
}
}
fclose(fd);
}
if (foundTag)
return value;
return NULL;
}
FWIW, RHEL/Fedora/CentOS have /etc/sysconfig/clock:
ZONE="Europe/Brussels"
UTC=true
ARC=false
I liked the post made by psmears and implemented this script to read the first output of the list. Of course there must have more elegant ways of doing this, but there you are...
/**
* Returns the (Linux) server default timezone abbreviation
* To be used when no user is logged in (Ex.: batch job)
* Tested on Fedora 12
*
* #param void
* #return String (Timezone abbreviation Ex.: 'America/Sao_Paulo')
*/
public function getServerTimezone()
{
$shell = 'md5sum /etc/localtime';
$q = shell_exec($shell);
$shell = 'find /usr/share/zoneinfo -type f | xargs md5sum | grep ' . substr($q, 0, strpos($q, '/') - 2);
$q = shell_exec($shell);
$q = substr($q, strpos($q, 'info/') + 5, strpos($q, " "));
return substr($q, 0, strpos($q, chr(10)));
}
In my Brazilian Fedora 12, it returns:
Brazil/East
And does exactly what I need.
Thank you psmears
Here's code that works for most versions of Linux.
#include <iostream>
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
using namespace std;
void main()
{
char filename[256];
struct stat fstat;
int status;
status = lstat("/etc/localtime", &fstat);
if (S_ISLNK(fstat.st_mode))
{
cout << "/etc/localtime Is a link" << endl;
int nSize = readlink("/etc/localtime", filename, 256);
if (nSize > 0)
{
filename[nSize] = 0;
cout << " linked filename " << filename << endl;
cout << " Timezone " << filename + 20 << endl;
}
}
else if (S_ISREG(fstat.st_mode))
cout << "/etc/localtime Is a file" << endl;
}
According to this page, it looks like if you #include <time.h> it will declare the following.
void tzset (void);
extern char *tzname[2];
extern long timezone;
extern int daylight;
Does that give you the information that you need?
On Linux, I need to find the current timezone as an Olson location. I want my (C or C++) code to be portable to as many Linux systems as possible.
If you want to be portable, then use only GMT internally. Due to multi-user heritge, *NIX system clock is normally is in GMT and there is no system wide timezone - because different users connected to the system might be living in different timezones.
The user specific timezone is reflected in TZ environment variable and you might need to use that only when converting internal date/time into the user readable form. Otherwise, localtime() takes care of it automatically for you.
The libc accesses the Olson database when tzset is called, and uses simplified time zones afterwards. tzset looks at the TZ environment variable first, and falls back to parsing the binary data in /etc/localtime.
At first systemd standardised on having the Olson time zone name in /etc/timezone, Debian-style. After systemd 190 and the /usr merge, systemd only reads and updates /etc/localtime, with the extra requirement that the file be a symlink to /usr/share/zoneinfo/${OLSON_NAME}.
Looking at TZ, then readlink("/etc/localtime"), is the most reliable way to match the libc's tzset logic and still keep symbolic Olson names. For systems that don't follow the systemd symlink convention, reading /etc/timezone (and possibly checking that /usr/share/zoneinfo/$(</etc/timezone) is the same as /etc/localtime) is a good fallback.
If you can live without symbolic names, parsing the /etc/localtime tzfile is as portable as it gets, though a lot more complex. Reading just the last field gets you a Posix time zone (for example: CST5CDT,M3.2.0/0,M11.1.0/1), which can interoperate with a few time-handling libraries, but drops some of the metadata (no historical transition info).
Since tzselect was not mentioned by anyone and you do need a nearly goof-proof solution, work with what Olson did. Get the tzcode and tzdata files from elsie, plus tab files.
ftp://elsie.nci.nih.gov
In March 2017, the correct location to download from would be ftp://ftp.iana.org/tz/releases (and download tzcode2017a.tar.gz and tzdata2017a.tar.gz).
Then get tzselect.ksh from the glibc download. Then you can see how to reverse engineer timezones. One sticking point: you WILL sometimes have to ask what country and city the linux box is in. You can serialize that data if you want, and then verify it against the timezone data you can find.
There is no way to do this reliably all the time without the possibility of user intervention, for example, as part of program installation.
Good luck on Arizona in general, and in Western Indiana.... hopefully your code is going to run elsewhere.
The code below was tested successfully in bash shell on
SUSE Linux Enterprise Server 11
Ubuntu 20.04.5 LTS
CentOS Linux release 7.9.2009
Shell code:
echo $(hash=$(md5sum /etc/localtime | cut -d " " -f 1) ; find /usr/share/zoneinfo -type f -print0 | while read -r -d '' f; do md5sum "$f" | grep "$hash" && break ; done) | rev | cut -d "/" -f 2,1 | rev
Result example:
Europe/Vienna

Why can't QFile read from the "~" directory?

I've tried the following short example to find out about a bug in a bigger program I am working on. It looks like QFile doesn't support unix (or the shell's) notation for the home directory:
#include <QFile>
#include <QDebug>
int main()
{
QFile f("~/.vimrc");
if (f.open(QIODevice::ReadOnly))
{
qDebug() << f.readAll();
f.close();
}
else
{
qDebug() << f.error();
}
}
As soon as I replace the "~" with my real home directory path, it works. Is there an easy workaround - some setting to enable? Or do I have to go the "ugly" way and ask QDir for the home directory of the current user and prepend that manually to each path?
Addendum: It's clear that usually the shell performs the tilde expansion so programs would never see that. Still it is so convenient in unix shells that I hoped the Qt implementation for file access would have that expansion included.
You can just create a helper function to do this for you, something like:
QString morphFile(QString s) {
if ((s == "~") || (s.startsWith("~/"))) {
s.replace (0, 1, QDir::homePath());
}
return s;
}
:
QFile vimRc(morphFile("~/.vimrc"));
QFile homeDir(morphFile("~"));
A more complete solution, allowing for home directories of other users as well, may be:
QString morphFile(QString fspec) {
// Leave strings alone unless starting with tilde.
if (! fspec.startsWith("~")) return fspec;
// Special case for current user.
if ((fspec == "~") || (fspec.startsWith("~/"))) {
fspec.replace(0, 1, QDir::homePath());
return fspec;
}
// General case for any user. Get user name and length of it.
QString name (fspec);
name.replace(0, 1, ""); // Remove leading '~'.
int len = name.indexOf('/'); // Get name (up to first '/').
len = (len == -1)
? name.length()
: len - 1;
name = name.left(idx);
// Find that user in the password file, replace with home
// directory if found, then return it. You can also add a
// Windows-specific variant if needed.
struct passwd *pwent = getpwnam(name.toAscii().constData());
if (pwent != NULL)
fspec.replace(0, len+1, pwent->pw_dir);
return fspec;
}
Just one thing to keep in mind, the current solution is not portable to Windows (as per the comments in the code). I suspect this is okay for the immediate question since .vimrc indicates that's not the platform you're running on (it's _vimrc on Windows).
Tailoring the solution to that platform is possible, and indeed shows that the helper-function solution is a good fit since you'll only have to change one piece of code to add that.
It has nothing to do with not supporting UNIX; the expansion of tildes to the user's home directory is a substitution performed by the shell, so yes, you will have to manually replace them.
Please submit a suggestion to the Qt bugtracker.
https://bugreports.qt.io/
Take a look at the C library function glob, which will do tilde expansion (and possibly wildcard expansion and various other functions too).