this program is working properly under window but it gives segmentation fault under unix
Can u find where i m mistaking....
u can give command line arguments like this
./myprogram -a filename.txt for sortin filename in ascending order
./myprogram -r filename.txt for sorting filename in reverse order
Program
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_LEN 100 /* Length of input buffer */
#define NUM_P 100 /* maximum number of strings */
#define TRUE 1
#define FALSE 0
void main(int argc, char *argv[])
{
FILE *fp;
char buffer[BUFFER_LEN]; /* space to store an input string */
char *pS[NUM_P] = { NULL }; /* Array of string pointers */
char *pTemp = NULL; /* Temporary pointer */
int i = 0, a=0; /* Loop counter */
int sorted = FALSE; /* Indicated when strings are sorted */
int last_string = 0; /* Index of last string entered */
if(strcmp(argv[1],"-a")==0)
a=1;
if(strcmp(argv[1],"-r")==0)
a=2;
fp =fopen(argv[2],"r"); /* Opening the file in read mode */
while((*fgets(buffer,(BUFFER_LEN-1),fp) != '\0') && (i < NUM_P))
{
pS[i] = (char*)malloc(strlen(buffer) + 1);
if(pS[i]==NULL) /* Check for no memory allocated */
{
printf(" Memory allocation failed. Program terminated.\n");
return;
}
strcpy(pS[i++], buffer);
}
last_string = i; /* Save last string index */
switch(a)
{
case 1:
{
/* Sorting in ascending order */
while(!sorted)
{
sorted = TRUE;
for (i = 0 ; i < last_string - 1 ; i++)
if(strcmp(pS[i], pS[i + 1]) > 0)
{
sorted = FALSE; /* We were out of order */
pTemp = pS[i]; /* Swap pointers pS[i] */
pS[i] = pS[i + 1]; /* and */
pS[i + 1] = pTemp; /* pS[i + 1] */
}
}
break;
}
case 2:
{
/* Sorting in decending order */
while(!sorted)
{
sorted = TRUE;
for (i = 0 ; i < last_string - 1 ; i++)
if (strcmp(pS[i], pS[i + 1]) < 0)
{
sorted = FALSE; /* We were out of order */
pTemp = pS[i]; /* Swap pointers pS[i] */
pS[i] = pS[i + 1]; /* and */
pS[i + 1] = pTemp; /* pS[i + 1] */
}
}
break;
}
default:
{
printf("wrong argument passed");
exit(1);
}
}
/* Displayed the sorted strings */
printf("\nYour input sorted in order is:\n\n");
for (i = 0 ; i < last_string ; i++)
{
printf("%s\n", pS[i] );
free( pS[i] );
pS[i] = NULL;
}
}


