Search code examples
c++ifstream

ifstream not opening file


In this function i am trying to open a file that contains a set of characters that i want to assign to my matrix array, however whenever i run this program the console displays an error that says that the file is not open. Another question, if i add that file to my resource folder how do i specify to access that file and not the one that i have in the root of my hard drive?

ifstream readSecondMap("C:\\map_2.txt", ifstream::in);

void Stage::populateStage(ifstream &myStage, char (&myArray)[mapXcor][mapYcor]) {
    if(myStage.is_open()){
        for(int a = 0; a < mapXcor+1; ++a){
            for(int b = 0; b < mapYcor+1; ++b){
                myArray[a][b] = (char) myStage.get();
            }
        }
        myStage.close();        
    } else {
        std::cout << "Error: Unable to open File" <<std::endl;
    }
}

Solution

  • Just as @TianyunLing noted:

    I've tested on KUbuntu 12.10:

    1. Open error: if map_2.txt does not exist, the error will occur.
    2. File path:

      folder1
      +------- file1
      +------- file2
      folder2
      +------- program
      +------- file3

    for your program to visit file1, use "../folder1/file1", to visit "file3", use file3. (suppose that you don't change your program working directory)

    One more thing, you don't need to specify ifstream::in for ifstream.