tags:

views:

281

answers:

3

I am trying to open a file in c++ and the server the progam in running on is based on tux.

string filename = "../dir/input.txt"; works but
string filename = "~jal/dir1/dir/input.txt"; fails

Is there any way to open a file in c++ when the filename provided is in the second format?

+12  A: 

The ~jal expansion is performed by the shell (bash/csh/whatever), not by the system itself, so your program is trying to look into the folder named ~jal/, not /home/jal/.

I'm not a C coder, but getpwent() may be what you need.

grawity
+1 for remembering the basics... duh....
ojblass
I meant duh by me not the poster of the question.
ojblass
Magnus, $HOME contains *your* homedir - and ~jal expands to the homedir of user 'jal'.
grawity
2Magnus: I'm not sure about $HOME, if program will run via 'su', for example
Alex Ott
+9  A: 

You could scan the string, replacing ~user by the appropriate directory.

The POSIX function wordexp does that, and a few other things

  • variable substitution, like you can use $HOME
  • optional command substitution, like $(echo foo) (can be disabled)
  • arithmetic expansion, like $((3+4))
  • word splitting, like splitting ~/a ~/b into two words
  • wildcard expansion, like *.cpp
  • and quoting, like "~/a ~/b" remains that
Johannes Schaub - litb
+1, I didn't know about wordexp.
zvrba
+3  A: 

Here is a ready piece of code, that performs this task:

How do I expand `~' in a filename like the shell does?

Alex Ott