//
you're reading...
Uncategorized

Basic File Processing Operations in C++

Basic file processing operations – writing random numbers


#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;

int main () {
  cout << "Opening output file stream" <<endl;
  ofstream myfile("./example.txt");
  if (myfile.is_open()) {
  for (int i=0; i < 1000; i++){
     myfile << rand() << endl;
  }
  }
  else cout << "Error opening file" << endl;
  myfile.close();
  return 0;
}

Basic file processing operations – reading and filtering data

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ifstream myfile;
  int top10[10]={0};
  int counter[10]={0};
  int index = 0;
  cout<< "Opening input file 'example.txt'" <<endl;
  myfile.open("example.txt");
  if (myfile.is_open())
    {
      int data;
      while (myfile>>data)
	{ 
      cout << data << '\n';
      index = data%10;
      counter[index]++;
      if (data > top10[index]) {
	  top10[index] = data;
	}
    }
    myfile.close();
    cout << "    i    counter[i]     top10[i]" << endl;
    for (int i =0 ; i<10; i++){
      cout << i << ": "<< counter[i] << "  " <<top10[i] << endl;
    }
  }

  else cout << "Unable to open file"; 

  return 0;
} 

Advertisement

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: