1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
|
#include <stdafx.h>
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;
const int BUF_MAX = 1000;
void nullArray(char*, int);
void nullArray(char**, int);
void sortArray(char **arr, int max);
int theFunction(int lineLength, char ** &theLines, int len);//******************************
int main()
{
ifstream fin; //file input
int lineCount = 0;
char buffer[BUF_MAX];
int lineLength = 10;
char **theLines = new char*[lineLength];
//Open input file:
//cout << "Enter a file path:\n\t==> ";
//cin.getline(buffer, BUF_MAX);
fin.open("data.txt");//*** I only changed this name because a had a file with this name already that I could use**
//Check if open failed:
if(fin.fail())
{
cout << "File open failed. Exiting:\n";
return 1;
}
//Loop until end of file:
int len = 0;
while(!fin.eof())
{
while(len < lineLength)
{
fin.getline(buffer, BUF_MAX);
theLines[len] = new char[strlen(buffer)+1];//****************************
strcpy(theLines[len], buffer);//*****************************
nullArray(buffer, BUF_MAX);
len++;
}
lineLength = theFunction(lineLength, theLines, len);
}
sortArray(theLines, len);
for (int i = 0; i < len; i++)
cout << theLines[i]<< endl;
fin.close();
}
void nullArray(char *arr, int max)
{
for(int i = 0; i < max; i++)
*(arr + i) = '\0';
}
void nullArray(char **arr, int max)
{
for(int i = 0; i < max; i++)
for(int j = 0; j < max; j++)
(arr[i])[j] = NULL;
}
void sortArray(char **arr, int max)
{
char *temp;
//Iterate through all the lines in the array to find the shortest array:
for(int i = 0; i < max; i++)
for(int j = i + 1; j < max; j++)
if (strlen(arr[i]) > strlen(arr[j]))
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
/*!
Function to create a new double size array
*/
int theFunction(int lineLength, char ** &theLines, int len)
{
char** temp =0;
//Create the double size buffer
lineLength *= 2;
temp = new char*[lineLength];
if(!temp)
return 0;
//allocate the array pointers
int i =0, count =0;
for(; i < len; i++)
{
//we now try to allocate each array pointer in turn
//if allocation for a pointer fails - we will delete all
//previously allocated pointers
temp[i] = new char[strlen(theLines[i])+1]();
if(!temp[i])
{
for(; count < i; count++)
{
delete [] temp[count];
}
delete []temp;
lineLength=0;
break;
}
else
{
//copy old stuff
strcpy(temp[i],theLines[i]);
}
}
//We want to delete the old data
if (lineLength !=0)
{
for(count =0; count < len; count++)
{
delete [] theLines[count];
}
delete []theLines;
theLines = temp;
}
return lineLength;
}
|