As antiRTFM probably already knows...... You can use filestreams, to write, and read, to txt files.
For instance, heres something i coded, that asks you to enter in two lines of text. It then takes that text, puts it into a file named 'awesome'. If there is already a folder with that name, it deletes everything inside it, and puts in your new text. If it doesn't exist, it creates one. The "awesome" txt folder is located in....
C:\Users\username\Documents\VisualStudio2008
\Projects\your project name\your project name/awesome
Then, under the reading function, it opens the file up again, and shows you whats inside the awesome.txt.
So i hope this could help people.... I'm going to quickly follow up on a more indepth description of what the code does for anyone that wants to know...
One thing about my code, I added in the paremeters "ios::trunc" to overwrite any old files/create new ones. The truncate mode should be default, so you needn't put that in.
(P.S At the moment, I am trying to figure out how to read the txt folder, and assign variables from that, like variable 1=line 1 of the folder, type thing. Once i do, i can easily create a save system, which can have multiple save spots, then my specified save )
And heres the code
- Code: Select all
#include "stdafx.h"
#include <string>
#include <fstream>
#include <iostream>
#include <windows.h>
using namespace std ;
int reading();
void wait ();
void sleep( unsigned int uSeconds );
int main()
{
string a;
string b;
cout << "Enter in your first line, then second line, etc.\n\n";
getline( cin, a);
a.append ("\n");
getline( cin, b);
b.append ("\n");
;
cout << "Now i will write to the file, 'awesome'\n\n\n";
Sleep(2000);
string test = a;
test.append( b ) ;
cout << "\nWriting done!";
ofstream writer( "awesome.txt", ios::trunc) ; //making the file (truncate is what deletes the old files and starts new)
writer << test << endl; //assigning my string, test, to the file
cout << "\nhokay, it should've worked\n\n";
Sleep(2000);
if( ! writer ) //this checks if it actually created the file
{
cout << "Error opening file for output" << endl ;
Sleep(2000);
return -1 ;
}
wait ();
writer.close() ;
reading ();
return 0 ;
}
int reading() //This reads the file
{
int i ;
string line ;
cout << "\n In the reader function\n";
Sleep(2000);
ifstream reader( "awesome.txt", ios::in ) ; //reads the file
if( ! reader )
{
cout << "Error opening input file" << endl ;
Sleep(2000);
return -1 ;
}
else
for( i = 0; ! reader.eof() ; i++ ) //reads untill the end of file, and counts how many lines it goes through
{
getline( reader , line ) ;
cout << line << endl ;
}
reader.close() ;
cout << "Iterations: " << (i/2) << endl ;
Sleep(2000);
cout << "\nreader done reading\n";
wait ();
return 0 ;
}
void wait ()
{
cout << "\n\nJust type in anything and press 'enter' to continue\n\n";
char t;
cin >> t;
}
