Openning files

Apr 28, 2009 at 1:44pm
Hi,

why this does not work?

1
2
3
4
    string file_name;
    file_name = "/home/cristiano/matrix4.dat";
    ifstream iFile;
    iFile.open(file_name);


I think there is a problem with the variable type of file_name, but changing it from string to char still does not work.

1
2
3
4
    char file_name;
    file_name = "/home/cristiano/matrix4.dat";
    ifstream iFile;
    iFile.open(file_name);


Any help will be appreciated.

Thanks.
Last edited on Apr 28, 2009 at 1:47pm
Apr 28, 2009 at 2:17pm
Do these compile?

The first one should fail on line 4 as it can't convert a std::string to const char*.

The second should fail on line 2 as it can't convert a char to a const char *.
Apr 28, 2009 at 2:29pm
Hi kbw,

this do not compile!(..I think you verified.)

I want to know how do I need to declare file_name... In the way I can pass it to iFile.open(file_name);

Can you think in some way?

Because I want to store the file name path in a variable and then use that variable to load the file.

Apr 28, 2009 at 2:59pm
Try:
1
2
3
4
    std::string file_name;
    file_name = "/home/cristiano/matrix4.dat";
    std::ifstream iFile;
    iFile.open(file_name.c_str());


or even:
1
2
3
    std::string file_name;
    file_name = "/home/cristiano/matrix4.dat";
    std::ifstream iFile(file_name.c_str());

Apr 28, 2009 at 3:53pm
Thanks kbw,

it works!
Topic archived. No new replies allowed.