C snprintf indicates user home directory

I use snprintfto write formatted data to disk, but I have one problem, how can I save it in the user's home directory?

 snprintf(filename, sizeof(filename), "%s_%s.sho", client, id);
0
source share
3 answers

On Linux and POSIX systems, the home directory is often found from an environment variable HOME. So you can encode

snprintf(filename, sizeof(filename), "%s/%s_%s.sho", 
         getenv("HOME"), client, id);

Pedantically, getenv (3) may fail (or make a mistake). But this rarely happens. See environment (7) .

(You can check and / or use getpwuid (3) with getuid (2) ...)

setuid . , , ( ).

+2

, HOME .

getuid() getpwuid() , :

#include <unistd.h>
#include <pwd.h>

struct passwd *pwd = getpwuid( getuid() );

/* need to duplicate the string - we don't know
   what pw_dir points to */
const char *homeDir = strdup( pwd->pw_dir );

...

+3

getenv(3) HOME. , :

#include <stdlib.h>
#include <stdio.h>
int main(void) {
    printf("%s\n", getenv("HOME"));
    return 0;
}

filename , , .

This should work on any Unix-like system, including Linux, macOS, BSD, and possibly many others.

+2
source

Source: https://habr.com/ru/post/1677839/


All Articles