awiebe
awiebe

Reputation: 3836

Trouble opening file in C++

I'm having trouble opening a file for reading, and I can't quite figure out what I'm doing wrong, maybe something is wrong with how i give my path, but i don't know.

/*
output:
Where is the conversion table ?
/Users/awiebe/Documents/Langara\ Assignments/CPSC1160/CURRENCYCODES.txt 
Unable to open file
*/


StringFloatMap readFile(string path)
{
    //fstream filestr ("test.txt", fstream::in | fstream::out);
    ifstream filestr;
    const char* cPath = path.c_str();
    filestr.open(cPath);

    if (filestr.is_open())
    {
        filestr.close();
    }
    else
    {
        cout << "Unable to open file" << endl;
    }
/*…*/
}

Upvotes: 0

Views: 198

Answers (3)

Toby
Toby

Reputation: 3905

Just get rid of the "\" and give him the path: e.g.:

/Users/awiebe/Documents/Langara Assignments/CPSC1160/CURRENCYCODES.txt

Since you use the string class there is no need to use escape sequences for the whitespaces.

Upvotes: 0

alanxz
alanxz

Reputation: 2026

You don't need to escape the space character in the path (e.g., you can remove the \ in your filename).

Upvotes: 1

Adrian Cornish
Adrian Cornish

Reputation: 23868

The cPath variable is not needed (but maybe good for debugging)

I would suggest printing the failure message. Add

#include <cstring>
#include <cerrno>

and

cout << "Unable to open file:" << errno << ':' << strerror(errno) << std::endl;

Upvotes: 0

Related Questions