// test_fileio.cc open, read, change, write file #include #include // file IO stuff in here #include #include using namespace std; int main() { ifstream file_in; // object file_in of type istream (like cin) ofstream file_out; // object file_out of type ostream (like cout) char in_line[255]; // hold one line at a time (old C string) string line; // for manipulating line string char_val; // ASCII character string value int val; // binary value (integer) char out_val[6]; // reconverted ASCII string cout << "test_fileio expects a file named junk.txt to exists" << endl; // first just open file and read and print it file_in.open("junk.txt"); if(!file_in) { cout << "could not open file junk.txt" << endl; return 1; } while(!file_in.eof()) // loop to read the input file { file_in.getline(in_line, 255, '\n'); line = string(in_line); cout << line << endl; } file_in.close(); cout << " finished read and print of a file" << endl; // open again, now modify and write file_in.open("junk.txt"); if(!file_in) { cout << "could not open file junk.txt" << endl; return 1; } file_out.open("junk.out"); if(!file_out) { cout << "could not open file junk.out" << endl; return 1; } while(!file_in.eof()) // loop to read the input file { file_in.getline(in_line, 255, '\n'); line = string(in_line); cout << line << endl; if(line.length() < 1) break; // can't do zero length lines if(line.substr(8,4)==string("good") && line.length()>=18) { line.replace(8, 4, string("OK ")); // modify a field char_val = line.substr(12, 6); // extract a field istrstream buf(char_val.begin(), char_val.length()); buf >> val; // convert to binary cout << val << endl; ostrstream conv(out_val, 6); conv << val/2 ; // do some computation line.replace(12, 6, string(out_val)); } file_out << line << endl; } file_in.close(); file_out.close(); cout << "test_fileio finished." << endl; return 0; }