/* Author: Arun Somasundaram, CSE Dept, OSU. Simple program for File Input/Output (Txt and Binary Format) */ #include #include using namespace std; void writeTextFile(){ cout << "Writing text file" << endl; ofstream oFile; oFile.open("out.txt"); oFile << "Line 1 of file" << endl; oFile << "Line 2 of file"; oFile.close(); } void readTextFile(){ cout << "Reading text file" << endl; string line; ifstream iFile ("out.txt"); if (iFile.is_open()){ while (!iFile.eof()){ getline (iFile, line); cout << line << " 1 " << endl; } iFile.close(); } else { cout << "Unable to open file." << endl; } } void writeBinaryFile(){ cout << "Writing Binary file " << endl; ofstream oFile("out.bin", ios::binary); int num = 16; int *sequence = new int[num]; for(int i = 0; i < num; i++){ sequence[i] = i*i; } //write takes char * as first argument //So reinterpret_cast it oFile.write(reinterpret_cast(sequence), num*sizeof(int)); oFile.close(); delete [] sequence; } void readBinaryFile(){ cout << "Reading Binary file" << endl; ifstream iFile("out.bin", ios::binary | ios::ate); if (iFile.is_open()){ int num = iFile.tellg(); num /= sizeof(int); int *sequence = new int[num]; iFile.seekg(0, ios::beg); //read takes char * as first argument //So reinterpret_cast it iFile.read(reinterpret_cast(sequence), num*sizeof(int)); iFile.close(); for(int i = 0; i < num; i++){ cout << sequence[i] << " "; } delete [] sequence; } else { cout << "Unable to open file." << endl; } } int main(){ writeTextFile(); readTextFile(); writeBinaryFile(); readBinaryFile(); return 0; }