How to sort data file handling program without the concept of array in c++?
Answers
t:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
void Write_File(int num);
void Read_File(int num);
void Compare(int num);
//**********************
int main()
{
int num = 0;
cout << "Enter a positive number to generate random numbers ";
cin >> num;
Write_File(num);
Read_File(num);
Compare(num);
return 0;
}
//***************
// Functions Definitions
void Write_File(int num)
{
ofstream fout("sortfile.dat", ios::out | ios::binary | ios::beg);
int number = 0;
if (fout.is_open())
{
for (int x = 0; x < num; x++)
{
number = rand();
fout << number << endl;
}
fout.close();
}
else
{
cout << "Error, File not opened" << endl;
}
}
void Read_File(int num)
{
ifstream fin("sortfile.dat", ios::in | ios::binary | ios::beg);
int number = 0;
cout << endl << "randomly generated numbers befor sorting\n";
if (fin.is_open())//check first if open already
{
for (int i = 0; i < num; i++)
{
fin >> number;
cout << number << endl;
}
fin.close();
}
else
cout << "File not opened in read phase." << endl;
}
void Compare(int num)
{
int number = 0;
int temp = 0;
int hold = 0;
ifstream fin("sortfile.dat", ios::in | ios::binary | ios::beg);
if (fin.is_open())//check first if open already
{
for (int i = 0; i < num; i++)
{
fin >> number;
fin >> temp;
if (number > temp)
{
hold = temp;
temp = number;
number = hold;
}
else
{
ofstream fout("sortfile.dat", ios::out | ios::binary | ios::beg);
fout << number;
fout << temp;
}
ofstream fout("sortfile.dat", ios::out | ios::binary | ios::beg);
fout << number;
fout << temp;
}
cout << endl << "Nums after sort\n";
for (int i = 0; i < num; i++)
{
fin >> number;
cout << number << endl;
}
fin.close();
}
else
cout << "File not opened in read phase." << endl;
}