Search code examples
c++codelite

Can't find the text file?


Hi guys i run this code and everything is good but when i go to the containing folder i can't find the text file !!..

 #include <iostream>
#include <string>
#include <fstream>


int main(){
    std::ofstream out_file{"../mohamed.txt"};
    std::string line {};
    if(!out_file){
        std::cerr<<"problem creating file"<<std::endl;
        return 1;
    }
    std::cout<<"Enter a text to the out file : ";
    std::getline(std::cin,line);
    out_file<<line<<std::endl;

    out_file.close();
    return 0;

}

Solution

  • The important thing to notice about file paths is that they are relative to current working directory, not (necessarily) the path at which you find the executable!

    Let's say, for instance, your executable resides in /someLocalPath/myProject/bin and you do on command line:

    cd /someLocalPath/myProject
    bin/myExe some parameters
    

    Then, as current working directory is myProject, you'll find the output file in someLocalPath, not myProject

    To get a hint at where to look, you could print the current working directory to console, have a look at std::filesystem::current_path for how to get.