Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening a file on unix using c++

Tags:

c++

unix

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?

like image 422
Jaelebi Avatar asked May 31 '09 17:05

Jaelebi


2 Answers

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.

like image 195
user1686 Avatar answered Oct 14 '22 06:10

user1686


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
like image 32
Johannes Schaub - litb Avatar answered Oct 14 '22 06:10

Johannes Schaub - litb