user7977875
user7977875

Reputation:

Why doesn't this open the file in the directory of the program?

I have this short program:

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

int main (int argc, char * argv[]) {
  std::string homedir = std::getenv("HOME");
  std::string filename = argc > 1 ? argv[1] : (homedir + "/" + "file");
  std::cout << homedir << std::endl;
  std::cout << filename << std::endl;
  std::fstream file;
  file.open(filename, std::ios::out);
  file << "Yo yo waddup" << std::endl;
  file.close();
  return 0;
}

When I supply no arguments, it opens a file in the users home directory. That of course makes sense. But when I run it from a different directory like this:

$ ./folder/hometest examplefile

The program creates "examplefile" in my current directory instead of the directory where the program is.

Why exactly is this happening?

Upvotes: 0

Views: 72

Answers (1)

R Sahu
R Sahu

Reputation: 206627

Why exactly is this happening?

The program is behaving just as expected.

The file is opened relative to the current work directory, not where the executable is located.

If it didn't work that way,

  1. All your programs will have to work with absolute paths, or
  2. The location of the program will be flooded with files. First, that might not be possible because of permissions issue. Second, in a multi-user system, users will end up trying to create the same file names/directories.

Neither of the above is desirable.

Upvotes: 2

Related Questions