Reading and writing of C + + files 1. Writing files in text mode
#include <iostream>#include <fstream>using namespaceStdintMain () {intAr[] = {1123,123, +, $, the, +,2,3};//Method 1,ios::out meaning is also written in the way open streamOfstream Ofile1 ("./test.txt", ios::out);//Method 2Ofstream Ofile2; Ofile2.open ("./test.txt");if(!ofile1) {//File open failedCerr <<"Open Err"<< Endl; Exit1); } for(inti =0; I <sizeof(AR)/sizeof(int); ++i) {ofile1 << ar[i] <<" "; } ofile1.close ();}
2. Reading documents in text mode
#include <iostream>#include <fstream>usingnamespace std;int main(){ int ar[10]; ifstream ifile("./test.txt",ios::in); if(!ifile){ "open err" << endl; exit(1); } for(int010; ++i){ //用空格分割读进数组 ifile >> ar[i]; }}
3. Binary mode Write file
#include <iostream>#include <fstream>usingnamespace std;int main(){ int ar[] = {11,232,123123,1223,455,4,4,5,56,4,33}; ofstream ofile("./text2.txt", ios::out | ios::binary); if(!ofile){ "open err" << endl; } ofile.write((charsizeof(ar)); ofile.close();}
4. Binary mode read file
#include <iostream>#include <fstream>usingnamespace std;int main(){ int ar[10]; ifstream ifile("./text2.txt",ios::in | ios::binary); if(!ifile){ "open err" << endl; } ifile.read((charsizeof(ar)); ifile.close();}
5. Read and write files by location
- Read by position in text mode
Assuming the contents of the file: "1 12 222 3232 2232323", each number of bytes is different, not correctly read out the desired.
Workaround, use binary mode to read by location.
#include <iostream>#include <fstream>using namespaceStdintMain () {Ifstream ifile ("./test.txt", ios::in);if(!ifile) {Cerr <<"Open Err"<< Endl; }intIndexintValue while(1) {CIN >> index; IFILE.SEEKG (index, Ios::beg);//Move pointerIFile >> value; cout << value << Endl; } }
- Read by position in the binary mode
#include <iostream>#include <fstream>usingnamespace std; int main(){ ifstream ifile("./test.txt", ios::in | ios::binary); if(!ifile){ "open err" << endl; } int index; int value; while(1){ cin >> index; ifile >> value; cout << value << endl; }}
C + + file read and write