Code:
#include <stdio.h>
#include <string.h>
/***************************************
This program shall SORT!
Made by Mark Crick
©2005 Mark Crick
****************************************/
#define MAX 256
void readfileintoarray(char fileName[],char filebuffer[]);
void writefilefromarray(char fileName[],char fileBuffer[]);
void swapchar ( char* x, char* y );
void selectionsort ( char arr[], int size );
void splitString(char stringToSplit[],int startIndex, int endIndex, char string[], int size);
void getstring(char arr[], int size, int pointer, char stringToGet[]);
int main(int argc, char *argv[])
{
char fileBuffer[BUFSIZ];
if(argc == 2)
{
readfileintoarray(argv[1],fileBuffer);
selectionsort(fileBuffer,sizeof(fileBuffer));
writefilefromarray(argv[1],fileBuffer);
}
else
{
printf("Sort: Incorrect argument \n Syntax: Sort [file to sort]");
exit(1);
}
printf("Sort.exe Made by Mark Crick ©2005 Mark Crick \n");
return(0);
}
void writefilefromarray(char fileName[],char fileBuffer[])// This will write from buffer to the file
{
FILE *filePtr;
if((filePtr = fopen(fileName,"w")) != 0)
{
fwrite(fileBuffer, sizeof(fileBuffer[0]), sizeof(fileBuffer)/sizeof(fileBuffer[0]), filePtr);
fclose(filePtr);
}
else
{
printf("Sort: Could not read filename :%s\n",fileName);
exit(1);
}
}
void readfileintoarray(char fileName[],char filebuffer[])// This will read the text file into the buffer array
{
FILE *filePtr;
if((filePtr = fopen(fileName,"r")) != 0)
{
fread(filebuffer, sizeof(filebuffer[0]), sizeof(filebuffer)/sizeof(filebuffer[0]), filePtr);
fclose(filePtr);
}
else
{
printf("Sort: Could not read filename :%s\n",fileName);
exit(1);
}
}
void selectionsort (char arr[], int size )
{
int indexOfMin, pass, j;
char *stringj,*stringPass;
for ( pass = 0; pass < size - 1; pass++ )
{
indexOfMin = pass;
for ( j = pass + 1; j < size; j++ )
{
getstring(arr,size,j,stringj);
getstring(arr,size,pass,stringPass);
if(strcmp(stringj,stringPass) < 0)
{
indexOfMin = j;
}
}
swapchar ( &arr[pass], &arr[indexOfMin] );
}
}
void getstring(char arr[], int size, int pointer, char stringToGet[]) // will return -1 if nothing found
{
int i;
for(i = pointer; i < size;i++)
{
if(arr[i] == '\n' || arr[i] == '\0' || arr[i] == '\r')
{
splitString(stringToGet,arr[pointer],arr[i],arr,size);
break;
}
}
}
// swap function for char
void swapcharInArray()
{
}
void splitString(char stringToSplit[],int startIndex, int endIndex, char string[], int size)
{
int i;
for(i=0; i < size && i < endIndex; i++,startIndex++)
{
string[i] = stringToSplit[startIndex];
}
}