
<<<>>>Need C code advice with functions and sorting.<<<>>>
[...snip description of assignment...]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *[], int , int);
typedef int (*compfun) (void *, void *);
static char string[40];
FILE *fileread;
You only have space for one string. You'll need space for up to 100
strings. For instance, you could declare `char strings[100][41];'.
Note that you need 41 bytes to store a 40-character string, if you
include the null terminator.
int main(int argc, char *argv[])
{
argc=argc-1;
fileread=fopen(argv[1],"r");
if (fileread == NULL){
printf("Unable to open %s\n", argv[2]);
exit(EXIT_FAILURE);
}
while (fgets(string, 40, fileread) != NULL) {
if(isdigit(string)==1) /* I know it accepts chars but would this
still work? */
sort(string,40, );
if(isalpha(string)==1)
sort(string,40 );
}
return 0;
}
/* Bubble sort function for but it's in's only */
Ugh. Why not use qsort() inside sort()? It would be faster, I'm
sure. It would be valid, too, as long as you change `void *' to
`const void *' for your typedef of compfun.
void sort (char *lines[], int size, compfun cmp)
{
[...]
}
You know, now that I come to think of it, it would be more convenient
to use char * pointers in place of void * pointers, so maybe you'll
want to ignore my qsort() advice above. I'll assume you use char *
pointers below.
Okay, now I'm sure what you're having trouble with is the function
pointers. I think that you're expected to do something like this:
/* Sorts lexicographically in forward order. */
int
srt_lf (const char *a, const char *b)
{
return strcmp (a, b);
Quote:
}
/* Sorts lexicographically in reverse order. */
int
srt_lr (const char *a, const char *b)
{
return -strcmp (a, b);
Quote:
}
/* Sorts numerically in forward order.
Ignores overflow; a proper function that handles it is
left as a (trivial) exercise for the reader. */
int
srt_lr (const char *a, const char *b)
{
return atoi (a) - atoi (b);
Quote:
}
/* Sorts lexicographically in reverse order. */
int
srt_lr (const char *a, const char *b)
{
return atoi (b) - atoi (a);
Quote:
}
etc.
Then you have to decide which of these to pass to sort(). You'll want
to do something like this:
if (argc < 3)
sort_func = srt_lf;
else if (strchr (argv[2], 'r'))
{
/* Reverse order. Test for n and f. */
...
}
else if (strchr (argv[2], 'n'))
sort_func = srt_nf;
else if (strchr (argv[2], 'f'))
sort_func = srt_ff;
else
sort_func = srt_lf;
Of course you'll need to declare or prototype all those functions
before trying to use them that way.
There. I hope I've given enough detail that you'll be able to figure
out your assignment but not enough that I just gave you the answer.
--
"In My Egotistical Opinion, most people's C programs should be indented six
feet downward and covered with dirt." -- Blair P. Houghton
Please: do not email me copies of your posts to comp.lang.c
do not ask me C questions via email; post them instead