Sugihara
Sugihara

Reputation: 1101

C++ fstream open

I am able to create the files such as

f.open("file")
f.open("./path/file")
f.open("../path/file")

but not

f.open("~/path...)
f.open("/path...)

How do I get the absolute paths to work?

Upvotes: 1

Views: 4577

Answers (2)

Peter
Peter

Reputation: 36597

With f.open("~/path/....") it is necessary for you to expand the ~ in code. This is typically done by calling getenv("HOME") to retrieve the home directory, and replacing every occurence of '~' in the path with the home directory.

When working with absolute paths, like "/path/whatever", you need to check that f.open() succeeds. There are various reasons that f.open() might fail, including access control (protections that prevent opening a file), the file already being opened by another process, the directory does not exist, etc.

Notably, f.open(), when attempting to open a file within a directory, requires that all directories in the path already exist. It won't exercise some magic to make them exist. If you want that, you need to code it. Bear in mind that each phase (creating directories, etc) might fail.

Upvotes: 2

Mike Kinghan
Mike Kinghan

Reputation: 61282

By default, std::fstream::open(filename) opens filename for both input and output. Hence that file must exist and you must have write permission to it.

In your cases:

f.open("file")
f.open("./path/file")
f.open("../path/file")

you were lucky.

In your case:

f.open("~/path...")

you used the path-element ~, which means $HOME in the shell but just means ~ in C++.

In the case:

f.open("/path...")

you were unlucky: either the file didn't exist or you didn't have write permission.

If you want to open a file simply for input then either:

  • use std::ifstream
  • use std::fstream f; f.open(filename,std::ios_base::in);

If you want to open a file simply for output then either:

  • use std::ofstream
  • use std::fstream f; f.open(filename,std::ios_base::out);

Upvotes: 5

Related Questions