Would you please help me in writing a c code to read data from a file and perform 1)numeric sort, 2)alphabetical sort.
the file may contain data of any kind.Like it may contain only numbers,only names or a database of employees of a company.(which contains their employee id,name,designation and salary,....in different fields).Each line contains details of one employee.
Sorting has to be done based on field specified.i.e,if sorting has to be done considering 3rd field(designation),
alphabetical sort has to be performed.And if the specified field contains information other than name or designation numeric sort has to be performed.
I would prefer a c program to solve the above problem.

Nimra_1 commented: pl zwrite the +0

Dani AI

Generated

If the input can be either all-numeric, all-text, or a multi-field record and you need to sort by an arbitrary field, consider reading all rows into a dynamic array and using qsort with a comparator that switches between numeric and text comparison based on the chosen field. Precompute a sort key for each row once (to avoid repeatedly tokenizing inside the comparator): extract the Nth field, trim whitespace, detect whether it is numeric using strtod and an endptr, and store both the original text and (if numeric) the parsed value. Then your comparator can do numeric compare when both sides are numeric, otherwise fall back to a locale-aware string compare; add a tie-break on the original row index to make the result stable since qsort itself is not stable.

Example comparator sketch (after precomputing keys):

int cmp_row(const void *pa, const void *pb) {
    const Row *a = pa, *b = pb;
    if (a->is_num && b->is_num) {
        return (a->key_num > b->key_num) - (a->key_num < b->key_num);
    }
    int r = strcoll(a->key_text, b->key_text); /* locale-aware */
    if (r) return r;
    return (a->orig_idx > b->orig_idx) - (a->orig_idx < b->orig_idx);
}

Notes:

  • Use getline (POSIX) or fgets to read lines safely; getline handles arbitrary line length (man7.org).
  • If the file is CSV with quoted fields or embedded commas, do not use naive strtok; follow CSV rules (see RFC 4180).
  • qsort is O(n log n) and part of the C standard library (qsort docs). For case-insensitive text, normalize keys (e.g., lowercase copies) before sorting.

Recommended Answers

All 11 Replies

you make struct Employee has(id ,name,salary,....) and make every Employee as node in linked list
then
save linked list into file after fill some data

then
read data from file and you can sort data by bubble sort :
(if you need numeric sort then sort nodes by id )
or
(if you need alphabetical sort then sort nodes by name)

data for one Employee you need read from file ,has already in file or not?

Thank you.I tried sorting numerically.it worked.But alphabetical sort(i.e sorting based on names) is giving trouble.Can u please give the logic or the code for sorting "emp->name" field in my linked list.

The logic for sorting with string keys is no different than with numeric keys. The only difference is in the comparison, where with string keys you cannot use relational operators. Instead, compare with strcmp():

if (strcmp(a->name, b->name) < 0) {
    /* a->name is lexicographically smaller than b->name */
    ...
}

This is as opposed to the numeric way of just comparing directly:

if (a->id < b->id) {
    /* a->id is numerically smaller than b->id */
    ...
}

Other than that, your sorting algorithm shouldn't change unless you also move around the data (in which case some variation of strcpy() may be needed). But since you're already storing these records in structures, you can just copy the structure instances and all will be well.

deceptikon has solved the problem of sorting data by name

struct data  \\\<<<  data for every node 
{
char name[20];
int id;
};

struct node    \\\<<<  node for linked list
{
struct data;
struct node*prev;
struct node*next;
};

struct node*head;
struct node*tail;

void bubble_sort()  \\\<<< sorting  nodes by bubble sort
{ 
int i,j,size;
struct Node*current;
struct Node*temp;
     size=0;
     PCurrent=PHead;

     while(current)
       {
          current=current->Next;
            size++;         
        }

PCurrent=PHead; 

for(i=0;i<size;i++)
{
    for(j=0;j<size-i;j++)
    {

        if(strcmp(current->next->data.name,current->data.name)<0)  \\\<<< sorting alaphabetic
        {


                temp->data=current->data;
                current->data=current->next->data;
                current->next->data=temp->data;                      


        }
        else if(current->next->data.id>current->next->data.id)   \\\<<< sorting  nomarical
        {

                temp->data=current->data;
                current->data=current->next->data;
                current->next->data=temp->data; 

        }                 
    current=current->Next;

     }
 current=head;  


 }             




}

strcmp in string.h library

sorry you must declare struct node*current as public

current pointer used to point for current node which you stop on it

Guys thank you so much.I did get my programming working. But i dropped the idea of using linked list.instead, i used a two dimensional character array and stored the items scanned from the file opened in read i.e "r" mode in that char array. And then,i've sorted them using strcmp funtion using bubble sort method.
Thanks again guys.I didn't expect anyone to even bother about my question,but i'm happy now.

Guys thank you so much.I did get my programming working. But i dropped the idea of using linked list.instead, i used a two dimensional character array and stored the items scanned from the file opened in read i.e "r" mode in that char array. And then,i've sorted them using strcmp funtion using bubble sort method.
Thanks again guys.I didn't expect anyone to even bother about my question,but i'm happy now.

What's the role of "PCurrent=PHead; " (line31)?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.