Write a file in a specific path in C++

后端 未结 7 776
無奈伤痛
無奈伤痛 2020-11-30 10:29

I have this code that writes successfully a file:

    ofstream outfile (path);
    outfile.write(buffer,size);
    outfile.flush();
    outfile.close();
         


        
7条回答
  •  庸人自扰
    2020-11-30 10:50

    I was stuck on this for a while and have since figured it out. The path is based off where your executable is and varies a little. For this example assume you do a ls while in your executable directory and see:

    myprogram.out  Saves  
    

    Where Saves is a folder and myprogram.out is the program you are running.

    In your code, if you are converting chars to a c_str() in a manner like this:

    string file;
    getline(cin, file, '\n');
    ifstream thefile;
    thefile.open( ("Saves/" + file + ".txt").c_str() );
    

    and the user types in savefile, it would be

    "Saves/savefile.txt"   
    

    which will work to get to to get to savefile.txt in your Saves folder. Notice there is no pre-slashes and you just start with the folder name.

    However if you are using a string literal like

    ifstream thefile;
    thefile.open("./Saves/savefile.txt");
    

    it would be like this to get to the same folder:

    "./Saves/savefile.txt"  
    

    Notice you start with a ./ in front of the foldername.

提交回复
热议问题