How to import and export a text file in C++

Started by
13 comments, last by ShadowBranch 17 years, 8 months ago
Hi I am new to this forum and although I dont have as many posts as others I hope that people are still willing to help me. I am in the middle of making a simple game using openGL. I am in charge of the saving and restoring game state process. I am thinking to export the x and y and z coordinate of the player to a text file as a saving game process. Then, if I wish to restore the game, I can just import the text file, read the value and place it in the game. The logic is pretty simple but I don't know the hows on exporting and importing a text file in C++ and read it. I don't know if I'm posting in the right thread so please excuse me if I posted on the wrong thread. Thanks.
Advertisement
C++ provides an easy way to interact with files in the form of filestream objects. To make use of this you have to include the fstream header file and instantiate an fstream object. If you've done that it's much like outputting text in a console window.

#include <iostream>#include <fstream>using namespace std;int main(){    fstream fileobject ( "savedgamestate.txt" ); // open a filestream    string file;    while ( fileobject >> file ) {        cout << file << endl;    }    fileobject.close();    return 0;}


This is file I/O in it's simplest form I would say, however, you might want to read your file per-line and in that case it might be an idea to loop until the fileobject.eof() condition has been met and reading lines all the time with the getline() method.

A useful reference to the fstream library can be found here
Hi mr_google,

Juz to add on to what rogierpennink wrote:

1) Better to use ifstream for saving game and ofstream for restoring game, instead of generic fstream. It is clearer to whoever is going to maintain the code later.

2) Remember to turn on unit buffering for your output file streams. This is to prevent loss of data that you thought you had written to the file but was actually not.

3) You might want to think abit more about how to format your save game file to enable easy writing and parsing/retrieving, and also so that you can write more than just your player position to it.

I recently wrote a small file parsing/reading/writing library for my work. Let me know if you would like some sample code.


Regards,
Joshua


Quote:1) Better to use ifstream for saving game and ofstream for restoring game, instead of generic fstream. It is clearer to whoever is going to maintain the code later.
I though it was the other way around ifstream for restoring and ofstream for saving.

F-R-E-D F-R-E-D-B-U-R...G-E-R! - Yes!
Im sorry for being such a newbie on this but:

What are ifstream and ofstream?

Can anyone show me how to write a text, for example the word: Main into a textfile using ifstream or ofstream? And read the text back from the textfile?

Much appriciated for the help.
Quote:Original post by DigiDude
Quote:1) Better to use ifstream for saving game and ofstream for restoring game, instead of generic fstream. It is clearer to whoever is going to maintain the code later.
I though it was the other way around ifstream for restoring and ofstream for saving.


It should be the other way around... ifstream (read input-stream) for loading and restoring... ofstream (read output-stream) for saving.
Quote:Original post by mr_google
Im sorry for being such a newbie on this but:

What are ifstream and ofstream?

Can anyone show me how to write a text, for example the word: Main into a textfile using ifstream or ofstream? And read the text back from the textfile?

Much appriciated for the help.


// basic file operations#include <iostream>#include <fstream>using namespace std;int main () {  ofstream myfile;  myfile.open ("example.txt");  myfile << "Writing this to a file.\n";  myfile.close();  return 0;}


int main () {  string line;  ifstream myfile ("example.txt");  if (myfile.is_open())  {    while (! myfile.eof() )    {      getline (myfile,line);      cout << line << endl;    }    myfile.close();  }  else cout << "Unable to open file";   return 0;}
Yeah...typo...ifstream for reading the file to restore; ofstream to write to save file. :)

Here is some code you can use right away mr_google. 2 functions: one for writing to file, one for reading from file. Just save the below code into a header file and #include it in your source code. You can use the 2 functions right away.

1) As mentioned before, you need to think abit about your save file format. The functions below are just to show you how to read/write to file streams. You should design your own based on your unique program needs.

2) There is still the matter of converting what you read from (or write to) the save file, into integer/long/float/double that you are actually using in your game. Do look up the C Standard Libray functions "strtod", "strtol", "strtoul" and the C++ Standard Library class "ostringstream".




/*************************************************************
*CODE START
*************************************************************/

#ifndef STREAMREADWRITE__H
#define STREAMREADWRITE__H


#include <fstream>
#include <string>

using std::ofstream;
using std::ifstream;
using std::string;

inline bool FN_WriteToFile(string strInput, string strFileName = "GameSaveFile.txt")
{
ofstream out(strFileName);
if(!out)
return false;
out << strInput << endl;
return true;
}

inline bool FN_ReadFromFile(string& strOutput, string strFileName = "GameSaveFile.txt")
{
ifstream in(strFileName);
if(!in)
return false;
in >> strOutput;
return true;
}


#endif // STREAMREADWRITE__H

/*************************************************************
*CODE END
*************************************************************/




Joshua
if you're not "fluent" with C++ maybe it's not a good idea, but i would likle to mention Boost library Boost::Serialization.
http://www.boost.org/libs/serialization/doc/index.html
it's really powerfull:

with this all your load AND save code for a class is
class CMyClass
{
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & m_iMember;
ar & m_sString;
ar & m_pOtherClass;
}
int m_iMember;
string m_sString;
CMyClass* m_pOtherClass;
}
just to add my bit to this. This is th best algorithm I use for reading from files and then later writing to files. It's along the same lines and uses simple items to be converted to whatever you want later.

#include <iostream>
using namespace std;
#include <fstream>
#include <cstring>
#include <string>

bool ReadFrom(char File[255]){
fstream theFile;
theFile.open(File, ios::in);
if(theFile.is_open() == 0){
cout << "ERROR: Failed to open the file! Check the file name!\n";
return(false);
}
while(theFile.good()){
string buffer;
getline(theFile, buffer);
}
return(true);
}

bool WriteTo(char File[255]){
fstream theFile;
theFile.open(File, ios::out);
// to write a basic::string or others, use this
theFile << [your-stuff-here];
// to write a character, such as a linefeed i would suggest this
theFile.write("\n", 2);
// the write function has two params, info to write, length of info
}

This topic is closed to new replies.

Advertisement