Current user path in Linux? - linux

How can I get the current user path in Linux? It can be either with the GTK+ framework APIs, or plain C++.

Assuming you mean the current directory of the process:
The plain POSIX C function is getcwd().
In glib, there's also g_get_current_dir().

If you want to get home directory use getenv("HOME")

g_get_home_dir() from Glib is more cross-platform than getenv("HOME"). It also prefers /etc/passwd entries over the HOME variable for various reasons discussed at the aforementioned link.

Not sure whether you're wanting the contents of $PATH or the user's current working directory. However to cover both options...
PATH is an environment variable, so you can access this with getenv(), in this instance getenv("PATH"), and is defined in <stdlib.h>.
The current working directory can be obtained with getcwd(), and is defined in <unistd.h>.

Related

How to resolve system directories paths independently of system locale?

TLDR
I need to get paths to system directories like "Screenshots":
On an English system. I can just use this one:
C:/Users/User/Pictures/Screenshots
How do I get the path to "Screenshots" directory on a non-English system?
C:/Users/User/Pictures/[NAME]
Description
I have a file manager app, it displays system directories and loads them on click.
The app can run system commands via Powershell and use Node.js (preferred)
Problem
The problem is, it only works if the system has English system language.
Currently, to resolve the "Screenshots" directory path, the app simply joins the User directory with the word "Screenshots"
const pictures = electronRemote.app.getPath('pictures')
const screenshots = PATH.join(pictures, 'Screenshots')
link to the line in code
Expectedly, the C:/Users/User/Screenshots path only exists on English systems.
One way to solve this is to use short names, at least on Windows, I know that system directories have short names like SCREEN~1 and WALLPA~1 for Screenshots and Wallpapers directories, but if I use these names the paths will look like this:
C:/Users/User/SCREEN~1 instead of C:/Users/User/Screenshots throughout the app.
And even if I were to run these paths through a function to convert it to readable name, how would I know which word to replace it with? I need to get the name in the system's language.
Are these translations stored somewhere on the system? Can I just retrieve the translated directory name and use that in the code above?
Question
How do I make it to get / resolve the actual path of system directories like Screenshots and Wallpapers, independently of system locale?
If you know how to do it, could you please suggest the solution for all platforms (Win, Mac, Linux)?
Should I just use the short names like SCREEN~1 and then automatically replace all the occurrences in UI and also filter all paths through a function that replaces this short name with the actual path throughout the whole app? Seems like a lot of work, this approach

Is there a way to default Go's os package calls to run under a specific user

Basically I cant use os.Mkdir or os.MkdirAll because it will create the directories as root. I know I can go the exec.Cmd route and set the syscall.Credential{}. But thats a bit cumbersome and I have to remove and replace a lot of code.
I was wondering if there was anything global I can set so calls to the os package will be ran as a specified user.
Thanks in advance.
In general, a process will make system calls as the user that ran the process. Maybe seteuid is what you're looking for?

Filepath to Documents folder independent of User

Is there a way to construct a filepath that links to the Documents folder of the active user. So instead of C:\Users\User\Documents\ something like C:\Active_User\Documents\
ps. I try to make use of this in KNIME.
The file chooser elements in KNIME understand a URL in the form of "knime://knime.workflow" which accesses the current workflow location regardless of higher directory path.
You could also use a Java Variable Edit to get the username in Java, which you use to create a string that can be used by the File Reader (or other node) as a flow variable.
It depends on what you're trying to achieve.
You can use
C:\Users\%USERNAME%\Documents
which will use the environment variable %USERNAME% (= current user).
In C#/.NET you can use Environment.SpecialFolder.MyDocuments like this:
Console.WriteLine("GetFolderPath: {0}",
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
In Java System.getProperty("user.home"); should give you the right base diretory to start with.

Where/How to save a preferences file in a *nix command line utility?

I am writing a small command line utility. It should hopefully be able to run on OSX, UNIX and Linux.
It needs to save a few preferences somewhere, like in a small YAML config file.
Where would one save such a file?
Language: Python 2.7
OS: *nix
Commonly, these files go somewhere like ~/.rc (eg: ~/.hgrc). This could be the path to a file, or to a directory if you need lots of configuration settings.
For a nice description see http://www.linuxtopia.org/online_books/programming_books/art_of_unix_programming/ch10s03.html
I would avoid putting the file in the ~ directory only because it has gotten totally flooded with crap. The recent trend, at least on ubuntu, is to use ~/.config/<appname>/ for whatever dot files you need. I really like that convention.
If your application is named "someapp" you save the configuration in a file such as $HOME/.someapp. You can give the config file an extension if you like. If you think your app may have more than one config file you can use the directory $HOME/.someapp and create regular-named (not hidden) files in there.
Many cross-platform tools use the same path on OS X as on linux (and other POSIX/non-Windows platforms). The main advantage of using the POSIX locations isn't saving a few lines of code, but saving the need for Mac-specific instructions, and allowing Mac users to get help from the linux users in the community (without any need to translate their suggestions).
The other alternative is to put them in the "Mac-friendly" locations under ~/Library instead. The main advantage of using the Mac locations is basically "Apple says so"—unless you plan to sandbox your code, in which case the main advantage is that you can do so.
If you choose to use the Library locations, you should read About the OS X File System and OS X Library Directory Details in the File System Programming Guide, but here's the short version:
Almost everything: Create a subdirectory with your app's name or bundle ID (unless you're going out of your way to set a bundle ID, you'll get org.python.python, which you don't want…) under ~/Library/Application Support. Ideally you should use APIs like -[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:] to get the path; if not, you have to deal with things like localization, sandbox containers, etc. manually.
Anything that can be easily re-created (so it doesn't need to be backed up, migrated, etc.): An identically-named subdirectory of ~/Library/Caches.
Preferences: Use the NSUserDefaults or CFPreferences APIs instead. If you use your own format, the "old" way of doing things is to create a subdirectory under ~/Library/Preferences named with your app's name or bundle ID, and put your files in that. Apple no longer recommends that, but doesn't really recommend an alternative (short of "use CFPreferences, damnit!"); many apps (e.g., Aquamacs) still do it the old way, but others instead pretend they're not preferences and store them under Application Support.
In Python, this works as follows (leaving out the error handling, and assuming you're going by name instead of setting a bundle ID for yourself):
from Foundation import *
fm = NSFileManager.defaultManager()
appsupport = (fm.URLForDirectory_inDomain_appropriateForURL_create_error_(
NSApplicationSupportDirectory, NSUserDomainMask, None, True, None)[0].
URLByAppendingPathComponent_isDirectory_(
appname, True))
caches = (fm.URLForDirectory_inDomain_appropriateForURL_create_error_(
NSCachesDirectory, NSUserDomainMask, None, True, None)[0].
URLByAppendingPathComponent_isDirectory_(
appname, True))
prefs = NSUserDefaults.persistentDomainForName_(appname)

saving to /home/user/Documents in different locales / languages

In my linux python app for Fedora I want to save user's work to /home/user/Documents/MyCoolApp/TheirGreatWork.txt
But I am not sure how to find the "Documents" folder if the user is not using English as their default language.
What is the right way to determine the right path so that files go in their "Documents" folder.
EDIT
Here is a which comes up if you change locales... showing how paths can get easily changed.
I'd use the subprocess module to get the output of the command xdg-user-dir DOCUMENTS. For example:
import subprocess
documents_dir = subprocess.check_output(["xdg-user-dir", "DOCUMENTS"])
print documents_dir # This is what you're looking for.
There is no right way as the user may have changed their locale, which (fortunately) does not rename the directory. If you want a fixed place for files managed by your app, use ~user/.MyCoolApp or let the user specify the directory.

Resources