Archived

This topic is now archived and is closed to further replies.

gamedevrules

opening txt files?

Recommended Posts

Since this is such a basic question, I figure it would be a good learning experience for you to find out on your own. Use your head and most of all Google.

Hint: Look up C++ File Input Output, more specifically istream and ostream.

Have fun!

Share this post


Link to post
Share on other sites
In full:

#include <fstream>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::ifstream;
using std::string;
int main(int argc, char *argv)
{
ifstream iFile;
string str;
cout << "Please enter the name of the file to display:";
cin >> str;
iFile.open(str.c_str());
if(iFile.fail())
{
cout << "Failed to open file " << str << ". Exiting..." << endl;
return -1;
}
// grab data line by line
while(!iFile.eof())
{
getline(iFile, str);
cout << str;
}
cout.flush();
iFile.close();
return 0;
}

I originally wanted to do something fancy involving stream iterators, so it took me longer than 15 minutes.

[ GDNet Start Here | GDNet FAQ | MS RTFM | STL | Google ]
Thanks to Kylotan for the idea!

Share this post


Link to post
Share on other sites