Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct {
- int id;
- char firstname[64], surname[64], address[256], phonenr[32];
- } tPerson;
- enum {
- ID, FIRSTNAME, SURNAME, ADDRESS, PHONENUMBER
- } sortBy = PHONENUMBER;
- int comparePersons(const void *p1, const void *p2) {
- const tPerson * c1 = p1, *c2 = p2;
- switch (sortBy) {
- case ID:
- return c1->id - c2->id;
- break;
- case FIRSTNAME:
- return strcmp(c1->firstname, c2->firstname);
- break;
- case SURNAME:
- return strcmp(c1->surname, c2->surname);
- break;
- case ADDRESS:
- return strcmp(c1->address, c2->address);
- break;
- case PHONENUMBER:
- return strcmp(c1->phonenr, c2->phonenr);
- break;
- }
- return 0;
- }
- int main(int argc, char *argv[]) {
- tPerson array[1000];
- tPerson demo_arr[] = {
- { 0, "Frantisek", "Dobrota", "Blizka 23, 11100 Praha", "777666555444" },
- { 1, "Anna", "Peprna", "Daleka 1, Plzen", "606055444" },
- { 2, "Viliam", "Razny", "Hluboka 3", "257000111" },
- { 3, "Zdenek", "Pomaly", "Krizova 5", "800333444" },
- { 4, "Rene", "Drobny", "Vysehradska 3", "774888999" },
- { 5, "Brona","Chalupova", "Mladcova 4", "356222333" },
- { 6, "Cyril", "Metodej", "U Zahradek 123", "456321000" },
- { 7, "Adam", "Doe", "Riverside 111", "956321000" }
- };
- if (argc>1) //processing command line parameters here
- switch (argv[1][0]) {
- case 'i': sortBy = ID; break;
- case 'f': sortBy = FIRSTNAME; break;
- case 's': sortBy = SURNAME; break;
- case 'a': sortBy = ADDRESS; break;
- case 'p': sortBy = PHONENUMBER; break;
- default:
- printf("1. parameter is a character specifying which column will be the sorting key\n"
- "i: ID, f: first name, s: surname, a: address, p: phone number\n");
- }
- char buffer[200];
- int i=0;
- puts("Please enter content of a CSV file, end by CTRL+Z");
- while (fgets(buffer, 200, stdin)!=NULL && i<1000) {
- int status=sscanf(buffer, "%d;%[^;];%[^;];%[^;];%[^;\n];",
- &array[i].id, array[i].firstname, array[i].surname,
- array[i].address, array[i].phonenr);
- if (status==5) i++;
- else {
- printf("Error on line %d.: %s\n", i, buffer);
- }
- }
- int count = i;
- qsort(array, count, sizeof(tPerson), comparePersons); // sorting here
- for (int i=0; i<count; i++) //printing the results
- printf("%d; %s; %s; %s; %s\n", array[i].id, array[i].firstname, array[i].surname, array[i].address, array[i].phonenr);
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment