This article is used to practice writing and reading files! ! !
topic:
Writing and reading files
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; const int size = 5; int main(int *argc, int **argv) { ofstream outFile; outFile.open("data.txt");//Associate the object with the file int *num = new int[size]; cout << "Enter 5 data:"; for (int i = 0; i < size; i++)//Write the content of the file cin >> num[i]; for (int j = 0; j < size; j++) outFile << num[j] << " "; outFile.close(); ifstream inFile; inFile.open("data.txt"); if (!inFile.is_open())//Determine whether the file is successfully opened { cout << "The file was not opened successfully" << endl; exit(EXIT_FAILURE); } int *data = new int[size]; for (int k = 0; k < size; k++) inFile >> data[k]; inFile.close(); cout << "Reading file content:"; for (int l = 0; l < size; l++) cout << data[l] << " "; delete[] num; delete[] data; return 0; }
Knowledge used:
Steps for C++ file output:
(1) #include <fstream> (2) Create an ofstream object; (3) Associate the object with the file and use the open() method;
(4) Similar to using cout to use ofstream object;
Steps to read a file in C++:
(1) #include <fstream> (2) Create an ifstream object; (3) Associate the object with the file and use the open() method;
(4) Similar to using cin to use ifstream object; (5) #include<cstdlib> Use is_open() to judge whether the file is successfully opened; use the good() method to judge whether there is an error in the read data; use the eof() method to judge whether the file is reached Tail (EOF); use the fail() method to determine whether the EOF type matches;
References:
C++ Primer Plus 6th Edition