Input/ Output Streams
Total Page:16
File Type:pdf, Size:1020Kb
Input/ Output Streams
// writes formatted output to a file, using <<
#include
ofstream outfile("fdata.txt"); // create ofstream object
outfile << ch // insert (write) data << j << ' ' // needs space between numbers << d << str1 << ' ' // needs spaces between strings << str2; }
// reads formatted output from a file, using >>
#include
ifstream infile("fdata.txt"); // create ifstream object extract (read) data from it infile >> ch >> j >> d >> str1 >> str2;
cout << ch << endl // display the data << j << endl << d << endl << str1 << endl << str2 << endl; } // file output with strings #include
// file input with strings #include
ofstream outfile("TEST.TXT"); // create file for output for(int j=0; j // file input with characters #include // binary input and output with integers #include for(j=0; j for(j=0; j // saves person object to disk #include // reads person object from disk #include do // data from user to file { cout << "\nEnter person's data:"; pers.getData(); // get one person's file.write( (char*)&pers, sizeof(pers) ); // write to file cout << "Enter another person (y/n)? "; cin >> ch; } while(ch=='y'); // quit on 'n' file.seekg(0); // reset to start of file file.read( (char*)&pers, sizeof(pers) ); // read first person while( !file.eof() ) // quit on EOF { cout << "\nPerson:"; // display person pers.showData(); file.read( (char*)&pers, sizeof(pers) ); // read another } // person } // handles errors during input and output #include ofstream os; // create output stream os.open("a:edata.dat", ios::trunc | ios::binary); // open it if(!os) { cerr << "\nCould not open output file"; exit(1); } cout << "\nWriting..."; // write buffer to it os.write( (char*)buff, MAX*sizeof(int) ); if(!os) { cerr << "\nCould not write to file"; exit(1); } os.close(); // must close it for(j=0; j ifstream is; // create input stream is.open("a:edata.dat", ios::binary); if(!is) { cerr << "\nCould not open input file"; exit(1); } cout << "\nReading..."; // read file is.read( (char*)buff, MAX*sizeof(int) ); if(!is) { cerr << "\nCould not read from file"; exit(1); } for(j=0; j