Can someone tell me what am I doing wrong here? Thanks.
Code:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXINPUT 80
#define MAXLINES 200
int compare(const void *name1, const void *name2)
{
return strcmp((char *)name1, (char *)name2);
}
int main(void)
{
FILE *fp;
char *p;
char input[MAXINPUT];
char *lineptr[MAXLINES];
int i;
int nlines = 0;
printf("Name of file with names to sort: ");
fgets(input, MAXINPUT, stdin);
if ((p = strchr(input, '\n')) != NULL)
*p = '\0';
fp = fopen(input, "r");
if (fp == NULL) {
printf("%s could not be found...", input);
getchar();
return 1;
}
while ((fgets(input, MAXINPUT, fp)) != NULL) {
p = (char *)malloc(1 * sizeof(input));
strcpy(p, input);
lineptr[nlines++] = p;
}
fclose(fp);
qsort((void *)lineptr, nlines, sizeof(lineptr) / sizeof(lineptr[0]), compare);
fp = fopen("names.txt", "w");
if (fp == NULL) {
printf("names.txt could not be created...");
getchar();
return 1;
}
for (i = 0; i < nlines; i++)
fprintf(fp, "%s", lineptr[i]);
fclose(fp);
return 0;
}