简体   繁体   中英

fstream C++ Pathing

Hi guys so I quickly wrote a test program to show you the issue I am having.

I am using fstream to write data to a file for my game so they can load and save their variables.

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

int main()
{
std::ofstream outputFile;
outputFile.open("PlayerData"); // This creates the file


std::string Name;
int Age;

std::cout << "Your Name: ";
std::cin >> Name;
outputFile << Name << std::endl;
std::cout << "Your Age: ";
std::cin >> Age;
outputFile << Age << std::endl;


outputFile.close();


return 0;




}

When I run the program it creates the "PlayerData" file in:

Visual Studio 2013\\Projects\\TestFilePathing\\TestFilePathing

Everything works fine but I would like for instead of the PlayerData file being dumped into the TestFilePathing directory, i'd like to path it to be created into a sub directory for organization purposes.

Thanks :D

If you don't specify a path, the file will be created in the current directory, that is not normally a desired behavior. You have to specify a complete path in order to ensure the fille will be saved where you want. If you want to know the path of the current executable, you can use check this other SO question: https://stackoverflow.com/a/1528493/566608 . Once you have the path, you can choose a location in a path near to the executable to save the data. Or, if you prefer, use system folders ( depends on the Operating System how to know their names, in Windows check this . ) Never trust current directory as a path, or part of that, because user could always choose to run your program with a different current directory.

Use the subdirectory in the file path:

outputFile.Open("SubDirectory/PlayerData");

The reason it ends up in Visual Studio 2013\\Projects\\TestFilePathing\\TestFilePathing is that you have that directory as Working Directory in your debugging settings. (Check the configuration for the project). If you change that directory (or start the binary from the command line in another directory) that file with end up in that directory.

If you specify a relative path you will get this behaviour. Otherwise you can specify an absolute path and the file will end up there all the time regardless of what your working directory is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM