Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open file by its full path

Tags:

c++

file

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?


1 Answers

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);
like image 111
Konrad Rudolph Avatar answered Nov 21 '25 06:11

Konrad Rudolph