Hi all.
I am trying to write code that will write and read from a file in a different directory than the current directory, but its not going so good. Here is my most recent attempt (platform is Ubuntu Linux):
Code:
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <fstream>
using namespace std;
void writeToFile();
void readFromFile();
void writeToFile() {
ofstream out("Files/test.txt");
if (!out) {
cerr<< "Failed to open file. Exiting out...";
exit(0); //failed to open file
}
out<< "Line 1: Rock the boat.\n"
<< "Line 2: Rock the boat.\n"
<< "Line 3: Capasize the boat.\n"
<< "Line 4: ...and finally throw someone FROM the boat. YEA!!!"<<endl;
out.close();
}
char buf[100];
const int NUMBER_OF_LINES = 4;
int i = 0;
void readFromFile() {
ifstream in("Files/test.txt");
if (!in) {
cerr<< "Failed to open file. Exiting out...";
exit(0); //failed to open file
}
while (i < NUMBER_OF_LINES) {
in.getline(buf, 60);
cout<<buf;
cout<<'\n';
i++;
}
in.close();
}
int main() {
cout<< "This program will create a file if it doesn't already exist,\n"
<< "write some stuff to it, close the file, open it up again,\n"
<< "read from it, display its contents, and finally close the file again.\n\n"
<< "Press Enter to do this."<<endl;
cin.get();
writeToFile();
readFromFile();
return 0;
}
}
Trouble is, what ends up happening is the file gets created in the current directory, instead of in the /Files directory like intended, and not only that, the file name ends up being "Files est.txt" instead of "test.txt" like I wanted to have it.
Obviously, I don't understand how to specify a directory correctly in either an ifstream of ofstream.
Please help.
Thanks in advance.