How do i load files from the documents folder?

Started by
2 comments, last by LennyLen 11 years, 5 months ago
Hey guys.

How do i load from files in the documents folder on any computer?
I am making a game that have a highscore.txt file.

So far, how i load and save the highscore.txt file is kinda this way.

[source lang="cpp"]
int score = 0;
int highscore = 0;

std::ifstream inputfile;
inputfile.open("highscore.txt");
inputfile >> highscore;
inputfile.close();

/*
Play the game (gameloop)
*/
if(score > highscore)
{
std::ofstream outputfile("highscore.txt");
outputfile << score;
outputfile.close();
}
[/source]

But the problem is when i make an installer for my game, then i have to put the highscore.txt file in another folder (e.g my documents folder) than my original folder where all the images, dlls are. Otherwise i cant save my new highscore (only load) because the c: drive is protected and windows wont allow to edit it.

Ive tried to write something like this:

[source lang="cpp"]inputfile.open("C:\\Users\\Danny\\Documents\\highscore.txt");[/source]
It works, but "Danny" is my name and is of course not the same name as other peoples computers.

So what kind of code should i use/write to make it able to load and save in the highscore.txt file on the documentsfolder on any computer?
If u can help me (and if its gonna be a hard task), please, cut it in paper for me (post the code wink.png ), because im a big noob when it comes to new libraries or low-level programming or anything like that

Thanks alot!!! biggrin.png
Advertisement
You can use SHGetFolderPath() to get the location of the various special folders on the computer. The linked page has example code.
[source lang="cpp"]
TCHAR szPath[MAX_PATH];

if(SUCCEEDED(SHGetFolderPath(NULL,
CSIDL_PERSONAL|CSIDL_FLAG_CREATE,
NULL,
0,
szPath)))
{
PathAppend(szPath, TEXT("New Doc.txt"));
HANDLE hFile = CreateFile(szPath, ...);
}
[/source]

This is the example code.... and i dont understand a single line of it wacko.png .
How should i use/write/incorporate this code with my ifstream and ofstream?
Here's an example that will create the file in the correct place, and write 32 to it. You should be able to take it from there:

[source lang="cpp"]#include <windows.h>
#include <shlobj.h>
#include <sstream>
#include <fstream>

int main()
{
TCHAR szPath[MAX_PATH];
std::stringstream filename;
std::ofstream outputfile;

if(SUCCEEDED(SHGetFolderPath(NULL,
CSIDL_PERSONAL|CSIDL_FLAG_CREATE,
NULL,
0,
szPath)))
{
filename << szPath << "\\highscore.txt";
outputfile.open((filename.str()).c_str());
outputfile << 32;
outputfile.close();
}

return 0;
}
[/source]

This topic is closed to new replies.

Advertisement