Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to open a file in user's home folder

Tags:

c++

linux

i'd like to put a kind of lock file in the user's home directory on linux(from c++) but fopen'ing ~/.fluudit doesn't seem to work.

fopen("~/.fluudit","w");   //fails
like image 353
flownt Avatar asked May 27 '10 19:05

flownt


2 Answers

You can use the environment variable HOME and if that's not present, you can use the password database:

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

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

const char *homedir = pw->pw_dir;
like image 175
R Samuel Klatchko Avatar answered Nov 06 '22 17:11

R Samuel Klatchko


The expansion of ~ to, say, getenv("HOME") is called globbing and is something you need to do first. You didn't say which libaries or frameworks you are using, but some provide this.

like image 29
Dirk Eddelbuettel Avatar answered Nov 06 '22 18:11

Dirk Eddelbuettel