Jump to content

  • Log In with Google      Sign In   
  • Create Account

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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
14 replies to this topic

#1 mr_google   Members   -  Reputation: 120

Like
0Likes
Like

Posted 23 July 2006 - 10:16 PM

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.

Sponsor:

#2 Rogier Pennink   Members   -  Reputation: 400

Like
0Likes
Like

Posted 23 July 2006 - 10:31 PM

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

#3 Hot Dog   Members   -  Reputation: 115

Like
0Likes
Like

Posted 23 July 2006 - 10:59 PM

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




#4 KittyRa   Members   -  Reputation: 259

Like
0Likes
Like

Posted 24 July 2006 - 05:35 AM

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.



#5 mr_google   Members   -  Reputation: 120

Like
0Likes
Like

Posted 25 July 2006 - 06:07 PM

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.

#6 SanityAssassin   Members   -  Reputation: 199

Like
0Likes
Like

Posted 25 July 2006 - 06:30 PM

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.

#7 Anonymous Poster_Anonymous Poster_*   Guests   -  Reputation:

0Likes

Posted 25 July 2006 - 06:37 PM

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;
}



#8 Hot Dog   Members   -  Reputation: 115

Like
0Likes
Like

Posted 26 July 2006 - 10:41 PM

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

#9 peous   Members   -  Reputation: 182

Like
0Likes
Like

Posted 26 July 2006 - 10:48 PM

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;
}


#10 ShadowBranch   Members   -  Reputation: 115

Like
0Likes
Like

Posted 27 July 2006 - 11:42 AM

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
}

#11 Hot Dog   Members   -  Reputation: 115

Like
0Likes
Like

Posted 27 July 2006 - 10:23 PM

Quote:
Original post by ShadowBranch
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
}


Hello ShadowBranch,

Just some comments.

1) Your buffer is defined locally. You need to define your function in such a way as to return it before it is destroyed at end-of-scope.

2) Your WriteTo function has no return statement.



Regards,
Joshua

#12 Anonymous Poster_Anonymous Poster_*   Guests   -  Reputation:

0Likes

Posted 28 July 2006 - 12:29 AM

I learnt file I/O from this GameDev article, maybe it'll help you out:
Click clik

#13 CCF   Members   -  Reputation: 199

Like
0Likes
Like

Posted 28 July 2006 - 12:30 AM

Oops, got log out... here's the link again:

I learnt file I/O from this GameDev article, maybe it'll help you out:
Click clik

#14 Zahlman   Moderators   -  Reputation: 1682

Like
0Likes
Like

Posted 28 July 2006 - 05:11 AM

Quote:
Original post by ShadowBranch
just to add my bit to this. This is th best algorithm I use for reading from files and then later writing to files.


- You don't use anything from <cstring> in the illustrated program (thank goodness), so don't include it. (Technically, I don't use iostream below, but it's almost certain to be used in a full program, whereas you would only need to include cstring if you were using stuff like strlen() etc., which you really shouldn't be using in normal circumstances.)
- Declaring a parameter as 'char File[255]' is rather silly: it doesn't actually limit the input, and there is no reason to do so anyway. It's more useful to accept a string by const reference and convert it with .c_str(); a passed-in string literal then gets converted back and forth, but it will still work - whereas you can't pass a std::string to a function expecting const char*.
- Don't use .open() on an fstream that you just declared. Instead, use the constructor that takes the .open() arguments. Remember, initialization != assignment, and you should initialize variables to their initial value when you know what that is.
- is_open() returns a bool. You should treat bools as if they were, you know, boolean: don't compare them to literals in order to answer 'if' conditions, because they already are the type that fundamentally represents the answer to a yes-or-no question.
- Use ifstream and ofstream to be specific; then ios::in and ios::out respectively are implied.
- Don't put parentheses around the things you're going to return; 'return' is not a function but a keyword.
- It might be a good idea to actually return the stuff that is read from a file, so that something can be done with it. Doing all the processing inside ReadFile() would be horrendously poor code organization.
- Don't handle errors by printing a local message and then returning a status value. If you're determined to indicate the error with a status value, you should let the calling code print the message as part of its error handling. Here, however, I would recommend either throwing an exception, or just returning an empty data set.
- Use the 'while (reading operation)' idiom for looping over input files.
- There's no reason to invoke .write() to output characters, especially if all the other I/O is using formatted I/O via the operator<<. This operator is overloaded to handle chars, including character literals (such as '\n' - notice *single* quotes) in the way you would expect it to. Note that writing 2 bytes for "\n" would also write the null terminator into the file, which is often not what you want (although probably benign).


#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <exception>

using namespace std;

vector<string> ReadFile(const string& name){
ifstream theFile(name.c_str());
if (!theFile.is_open()) {
throw runtime_error("File not found");
}

vector<string> result;
string line;
while (getline(theFile, line)) {
result.push_back(line);
}

return result;
}




#15 ShadowBranch   Members   -  Reputation: 115

Like
0Likes
Like

Posted 28 July 2006 - 05:20 AM

Just as a note, That was just a chunk from my program that I pulled and modified very quickly. It wasn't supposed to be 100% accurate as it is originally from a class I created for file i/o. I assume that if a programmer is asking about File I/O, they have enough knowledge to correctly implement the bit. Again, that's from my class, so overall, the code is correct when in the class, not what I showed, hopefully a basic c++ programmer with even 6 months of experience could get that code working easily.

Just to make everyone happy, here is the proper code to use! This still utilizes the fstream only command as that will allow you to create a single file for read and write. but you can change it to use ifstream for in and ofstream for out.


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

class CFileIO{
public:
bool ReadFrom(string File);
bool WriteTo(string File);
void WriteToBuffer(string Info);

protected:
string buffer;
};

void CFileIO::WriteToBuffer(string Info){
buffer.clear();
buffer.assign(Info);
}

bool CFileIO::ReadFrom(string File){
fstream theFile;
theFile.open(File, ios::in);
if(!theFile.is_open()){
while(theFile.good()){
getline(theFile, buffer);
// call a processing command here
}
return(true);
}else{
return(false);
}

bool CFileIO::WriteTo(string File){
fstream theFile;
theFile.open(File, ios::out);
if(theFile.is_open()){
theFile << [your-stuff-here];
return(true);
}else{
return(false);
}
}


BTW, I use return() as it is the way I've always returned data. It allows me to see exactly what is returned. I was taught to not use () but I've found it is easier for me when I use them. Just a programming preference, We are not look for everyone to code the exact same way. That is why the original code is there. Not as an exact copy and paste but for someone to learn. How else if a person to learn how to code if people hand them full code sets? and say here just copy this to your program and call the function. I had to get a book called the C++ primer, then read it for file io. Next I got on websites and read more. Found more ways of doing, next I hit the IRC chat rooms and found more ways. Once I had this list, I found the way I liked the best. This is what this guys should do. Don't hand people full code and say it works here. They have to learn. They will take a basic function and in a year rewrite it as they have learned more, then maybe later again.

Not everyone wants to have code that they don't know how it works. Some of us like code that will work but only after we take a little bit to see how it works. I do this, hopefully everyone else does, if they don't we have some bad programmers out there.

[Edited by - ShadowBranch on July 28, 2006 12:20:37 PM]




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS