0

I have a code which is huge but I need help with one part. I made this function and it brings information of people from my .txt file.

If I want to sort it alphabetically (and with their ID ie. 123456 earlier than 132456 -this might be separate and optional), how to do this?

sortRecord() { int b; int c; FILE *fp; fp = fopen("suspectfile.txt", "r"); if (fp) while ((c = getc(fp)) != EOF) putchar(c); fclose(fp); } 
2
  • 1
    What's your C background? Are you familiar with arrays and the qsort function, or have you not seen this before? Commented Jan 3, 2015 at 21:38
  • @templatetypedef I'm familiar with arrays but not really with sorting. So qsort is a little bit far for me. (I'll do a research now.) Commented Jan 3, 2015 at 21:40

2 Answers 2

1

The code that you have written right now will open the file, read it one character at a time, and print those characters back to the console. If you just need to print the contents of the file in sorted order and don't need to manipulate the file contents later on, you could consider using the system command to run the command-line tool sort, which does this for you. For example:

system("sort suspectfile.txt"); 

This will handle everything for you, though it won't actually load the data into your program.

If you need to load the data into your program and then go sort it, your best bet is probably to load the file contents into an array (I'll leave those details to you, since you know the file format better than I do) and then to use the qsort function to arrange the data into ascending order. qsort needs you to provide it with an array to sort, the size of each element in the array, the number of elements, and a comparison function. Here's one way you could use it:

/* String comparison function for use by qsort. The parameters will be * void*'s that actually point at char*'s. */ int string_comparator(const void* one, const void* two) { return strcmp(*(char**)one, *(char**)two); } char** file_contents_array = /* ... load the file ... */ qsort(file_contents_array, /* number of elements in the array */, sizeof(char *), string_comparator); 

You now have the file contents in sorted order and can do whatever you'd like with them.

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

it really helped works flawless! (But I can't stop it, will a simple break; help me or are there any other solution?)
What do you mean by "I can't stop it?" That's odd.
0

Use qsort() in combination with alphasort(). Please be careful with the locale your program runs in—it influences the order generated by these functions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.