8

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?

0

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I meant duh by me not the poster of the question.
Magnus, $HOME contains your homedir - and ~jal expands to the homedir of user 'jal'.
2Magnus: I'm not sure about $HOME, if program will run via 'su', for example
you were almost right, you omitted only one sign /, instead of "~jal/dir1/dir/input.txt" it should look like "~/jal/dir1/dir/input.txt"
9

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

Comments

3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.