C++ file read write code sharing

  • 2020-04-02 03:07:51
  • OfStack

Write a program to count the number of lines in data.txt, and write all lines to data1.txt.

Algorithm tips:

Lines are separated by carriage returns, and the getline() function is terminated by carriage returns. Therefore, you can use the getline() function to read each row and count the number of rows with a variable I.

(1) implementation of the source code


#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
 
using namespace std;
 
int coutFile(char * filename,char * outfilename)
{
  ifstream filein;
  filein.open(filename,ios_base::in);
  ofstream fileout;
  fileout.open(outfilename,ios_base::out);
  string strtemp;
  int count=0;
  while(getline(filein,strtemp))
  {
    count++;
    cout<<strtemp<<endl;
    fileout<<count<<" "<<strtemp<<endl;
  }
  filein.close();
  fileout.close();
  return count;
}
 
 
void main()
{
  cout<<coutFile("c:\data.txt","c:\data1.txt")<<endl;
}

Here's another example:

The following C++ code writes the user's input to afile.dat and then programmatically reads it out and outputs it to the screen


#include <fstream>
#include <iostream>
using namespace std;
  
int main ()
{
   
  char data[100];
 
  // open a file in write mode.
  ofstream outfile;
  outfile.open("afile.dat");
 
  cout << "Writing to the file" << endl;
  cout << "Enter your name: ";
  cin.getline(data, 100);
 
  // write inputted data into the file.
  outfile << data << endl;
 
  cout << "Enter your age: ";
  cin >> data;
  cin.ignore();
   
  // again write inputted data into the file.
  outfile << data << endl;
 
  // close the opened file.
  outfile.close();
 
  // open a file in read mode.
  ifstream infile;
  infile.open("afile.dat");
  
  cout << "Reading from the file" << endl;
  infile >> data;
 
  // write the data at the screen.
  cout << data << endl;
   
  // again read the data from the file and display it.
  infile >> data;
  cout << data << endl;
 
  // close the opened file.
  infile.close();
 
  return 0;
}

The program compiles and executes and outputs the following results


$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

The above is all the content of this article, I hope you can enjoy it.


Related articles: