Originally posted by Inez
How to input information to another file? and how to recall stuffs from that file!? all in console(or is this possible in console?
for starters here is some very simple file input output (note that it's not much different then inputting/outputting to the console, this is not a coincidence..)
file output:
Code:
#include <iostream>
#include <fstream> //required for ofstream class
int main()
{
ofstream output("test.txt"); //ofstream objects output to files,
//pass name of file to constructor
output << 5; //output the integer 5 to file
output.close(); //close the file
return 0;
}
file input:
Code:
#include <iostream>
#include <fstream>
int main()
{
ifstream input("test.txt"); //ifstream objects read from file,
//pass existing filename to
//constructor
int x;
if(!input) { //can test if file does not exist, or other reasons..
cerr << "file error!" << endl;
}
input >> x; //read that integer we outputted earlier
cout << x; //output the integer to console to see if worked
input.close(); //close the file
return 0;
}
compile the code above. the first code snippet outputs an integer to a file called "test.txt", the second file reads that integer from "test.txt" and outputs to the console. i used the .txt extension (assuming you use windows) so that you can open the file up yourself and see that the integer is in there. run the program in a new directory (doing this makes things easier when dealing with file i/o).
also, you can output any built-in c++ data type you want (int, char, float ...); and as many as you want. problem is, you will have to know how many and of what type to read back from the file so you will have to organize this yourself. example:
int x = 5;
char c = 'a';
double z = 5.5;
output << x << c << z;
//then you have to input in the correct order:
input >> x >> c >> a;
and there are other things like what "EOF" is, can use it to read an unknown number of items from a file (kind of lets you know your file pointer has reached the end of file).
point is, you should really check out a good C++ book that covers this stuff in more detail; well worth it.