2

Can I set a default directory path to fstream in c++? If I say,

fstream fPointer("file1.txt",ios::in);

It should locate the file from, /home/[user]/[path]/file1.txt

It should automatically locate the directory ( /home/[user]/[path]/ ) Whenever I use fstream or ofstream.

Smith Dwayne
  • 2,675
  • 8
  • 46
  • 75

2 Answers2

1

fstream will open the file in the 'current' working directory (i.e. the directory the program was executed from). If you want this to change, use cd (windows) or cwd (Linux?) to set the current working directory before executing the program.

Alternatively, just specify the full path to the file in your constructor.

Neil
  • 11,059
  • 3
  • 31
  • 56
  • For Linux it is `chdir()` – Slava Jun 16 '16 at 12:52
  • @Slava chdir() is a C function for changing the current direction /after/ running the program. I was talking about the shell commands for changing directory before running the program. – Neil Jun 16 '16 at 13:03
  • shell command depends on shell and for sh/ksh/bash/csh it is `cd` not `cwd`. But this is programming question so it would be logical to tell OP how to change current dir in program. – Slava Jun 16 '16 at 14:41
1
std::string myDefaultDirectory = "/home/[user]/[path]/";

...

fstream fPointer(
    myDefaultDirectory + "file1.txt",
    ios::in);
Midas
  • 7,012
  • 5
  • 34
  • 52
ravenspoint
  • 19,093
  • 6
  • 57
  • 103