user2494741
user2494741

Reputation:

open file by its full path

I want to ask user the full path where the file exists and then keep the path in an array. So during the program I want to open the file that is exists in that place. but unfortunately I don't know how to open the file. I tried the following code but it's not true.

    string address;
    cin>>address;
    ifstream file(address);

How do I open the file this way?

Upvotes: 3

Views: 971

Answers (3)

CapelliC
CapelliC

Reputation: 60024

possibily a problem could be the presence of space in address.

Try using getline(cin, address) instead (thanks to Konrad to spot the problem, my C++ it's a bit rusty...)

Upvotes: 0

3wic
3wic

Reputation: 500

ofstream myfile;
myfile.open (adresse.c_str());

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545618

Actually that code works as it is – at least in the current version, C++11.

Before that, you need to convert the string to a C-style string:

ifstream file(address.c_str());

Although you should beware of spaces in the file’s path as CapelliC mentioned in his (now-deleted) answer; in order to ensure that the user can enter paths with spaces (such as “~/some file.txt”), use std::getline instead of the stream operator:

getline(cin, address);

Upvotes: 2

Related Questions