C++ simple text file to read and write

  • 2020-04-02 01:06:34
  • OfStack

The code is as follows:

#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 //Written to the file
 ofstream ofs;  //Provides the ability to write files
 ofs.open("d:\com.txt",ios::trunc); //When trunc opens a file, clear the existing file stream or create the file if it does not exist
 int i;
 char a = 'a';
 for(i = 1; i != 27; ++i)
 {
  if(i < 10)
  {
   ofs << "0" << i << "t" << a << "n";
   a ++;
  }
  else
  {
   ofs << i << "t" << a << "n";
   a ++;
  }
 }
 ofs.close();
 //Read the file to the console
 char buffer[256];
 ifstream ifs; //Provide file reading function
 ifs.open("d:\com.txt",ios::in);//In -- open the file and read it
 cout << "d:\com.txt" << " As follows: " << endl;
 while(!ifs.eof())  //Determine if the end of the stream is reached
 {
  ifs.getline(buffer, 256, 'n'); //Characters up to 256 or end at a newline
  cout << buffer << endl;
 }
 ifs.close();
}

Related articles: