// This program uses an fstream object to write data to a file. #include #include #include // Used by function: setprecision() using namespace std; // Function Headers int demofile_out_app(); int setprecision(); int writeThreeRows(); int main() { fstream dataFile; cout << "Opening file...\n"; dataFile.open("../Files/demofile.txt", ios::out); // Open for output cout << "Now writing data to the file.\n"; dataFile << "Jones\n"; // Write line 1 dataFile << "Smith\n"; // Write line 2 dataFile << "Willis\n"; // Write line 3 dataFile << "Davis\n"; // Write line 4 dataFile.close(); // Close the file cout << "Done.\n"; // Call functions (headers defined above main and body defined below main) int x = demofile_out_app(); int y = setprecision(); int z = writeThreeRows(); return 0; } int demofile_out_app() { ofstream dataFile; cout << "Opening file...\n"; // Open the file in output mode. dataFile.open("../Files/demofile.txt", ios::out); cout << "Now writing data to the file.\n"; dataFile << "Jones\n"; // Write line 1 dataFile << "Smith\n"; // Write line 2 cout << "Now closing the file.\n"; dataFile.close(); // Close the file cout << "Opening the file again...\n"; // Open the file in append mode. dataFile.open("./Files/demofile.txt", ios::out | ios::app); cout << "Writing more data to the file.\n"; dataFile << "Willis\n"; // Write line 3 dataFile << "Davis\n"; // Write line 4 cout << "Now closing the file.\n"; dataFile.close(); // Close the file cout << "Done.\n"; return 0; } // This program uses the setprecision and fixed // manipulators to format file output. int setprecision() { fstream dataFile; double num = 17.816392; dataFile.open("../Files/numfile.txt", ios::out); // Open in output mode dataFile << fixed; // Format for fixed-point notation dataFile << num << endl; // Write the number dataFile << setprecision(4); // Format for 4 decimal places dataFile << num << endl; // Write the number dataFile << setprecision(3); // Format for 3 decimal places dataFile << num << endl; // Write the number dataFile << setprecision(2); // Format for 2 decimal places dataFile << num << endl; // Write the number dataFile << setprecision(1); // Format for 1 decimal place dataFile << num << endl; // Write the number cout << "Done.\n"; dataFile.close(); // Close the file return 0; } // This program writes three rows of numbers to a file. int writeThreeRows() { const int ROWS = 3; // Rows to write const int COLS = 3; // Columns to write int nums[ROWS][COLS] = { 2897, 5, 837, 34, 7, 1623, 390, 3456, 12 }; fstream outFile("../Files/table.txt", ios::out); // Write the three rows of numbers with each // number in a field of 8 character spaces. for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { outFile << setw(8) << nums[row][col]; } outFile << endl; } outFile.close(); cout << "Done.\n"; return 0; }