// test_file_io.cpp create a file, write file, close, open, read file #include // this should also includes in iostream #include // but don't count on it, yet #include // for input buffer using namespace std; // bring standard names into scope int main(int argc, char *argv[]) // standard main program definition { fstream my_io; // a users variable that holds stream information string word; // just a place for inputting cout << "test_file_io running" << endl;// just let user know the program is executing my_io.open("junk_file", ios::out); // creates file if necessary and opens file if(!my_io) // believe it!, anything can go wrong { cout << "can not open junk_file for writing" << endl; // common error message return 1; // common error exit } my_io << "Some text" ; // write to the file named "junk_file" my_io << 42; // write more my_io << "more text" << endl; // finish a line, '\n' new line character written my_io << "line 2" << endl; my_io.flush(); // force file to disk. Do not do this for scratch files. my_io.close(); // close the file cout << "junk_file written" << endl; // file should be written my_io.open("junk_file", ios::in); // open an existing file for reading if(!my_io) // believe it!, anything can go wrong { cout << "can not open junk_file for reading" << endl; // common error message return 1; // common error exit } // notice that character translation is taking place, each word is input, not a line my_io >> word; cout << word; my_io >> word; cout << word; my_io >> word; cout << word; my_io >> word; cout << word; my_io >> word; cout << word; // output is: // Sometext42moretextline2 // // But junk_file contains: Note no space around '42', five(5) "words" // Some text42more text // line 2 // no string my_io.get(word, 70); cout << word; // no my_io.getline(word); cout << word; my_io.close(); // just being neat, closing file being read return 0; }