Apr 29, 2015 at 6:05pm UTC
So in my C++ program, we have to first read data from a file. So for that I have declared my inputFile to be ifstream. But then later in the program, I want to write more data to that file. But to do that, my inputFile has to be ofstream.
So I do I do that ?
Apr 29, 2015 at 6:27pm UTC
From my understanding if you want a file to be read from - and to read from it, you need to define it as fstream
If you want to read up a little more on files, go right ahead:)
http://www.cplusplus.com/doc/tutorial/files/
Apr 29, 2015 at 6:52pm UTC
Something I'm been playing with and learning how to read and write from files..
My code doesn't add text to an already made text file tho.. I'm sure you code do something like... open file.. jump to end of file.. and then add text.. haven't gotten that far yet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void WriteToFile();
void ReadFromFile();
void LoadMap(vector<string> &mapdata);
void PrintMap(vector<string> mapdata);
int main()
{
vector<string> Map;
//WriteToFile();
//ReadFromFile();
LoadMap(Map);
PrintMap(Map);
system("PAUSE" );
return 0;
}
void WriteToFile()
{
ofstream file;
file.open("MyFile.txt" );
if (file.fail())
{
cout << "ERROR: Could not open file!" << endl;
perror("MyFile.txt" );
cout << "ERROR: Could not open file!" << endl;
}
file << "Map:test" << endl;
file << "XXX" << endl;
file << "XXX" << endl;
file << "XXX" << endl;
file.close();
cout << "Writing to file was a Succses!" << endl;
}
void ReadFromFile()
{
ifstream file;
file.open("MyFile.txt" );
if (file.fail())
{
cout << "ERROR: Could not open file!" << endl;
perror("MyFile.txt" );
cout << "ERROR: Could not open file!" << endl;
}
string lineContent;
while (getline(file, lineContent))
{
cout << lineContent << endl;
}
cout << endl;
file.close();
cout << "Reading from file was a Succses!" << endl;
}
void LoadMap(vector<string> &mapdata)
{
ifstream file;
file.open("MyFile.txt" );
if (file.fail())
{
cout << "ERROR: Could not open file!" << endl;
perror("MyFile.txt" );
cout << "ERROR: Could not open file!" << endl;
}
string lineContent;
while (getline(file, lineContent))
{
mapdata.push_back(lineContent);
}
file.close();
}
void PrintMap(vector<string> mapdata)
{
for (auto i = mapdata.begin(); i != mapdata.end(); ++i)
{
cout << *i << endl;
}
}
Last edited on Apr 29, 2015 at 6:52pm UTC