1. (20 points) Write a C program that sorts the lincs in a text file (considerin
ID: 3714262 • Letter: 1
Question
1. (20 points) Write a C program that sorts the lincs in a text file (considering cach linc as a string) using the library function gsort. So for cxample if the file contains lines "hello, abede£" "end, and aaaa,the program should print abedef helio The program should take the name of the file to sort as a command-line argument (and print appropriate error messages if none is given or the one given cannot be opened) and write the result of the sort to standard output To do this, I think you will need to read the whole file into memory. There are various ways to do this and perform the sort; the one I want you to use is somewhat involved but intended to give you more practice working with pointers. To ge full credir you must use the approach described here o First, read the whole file into memory. To do this you will need to know its size, and interestingly enough there doesn't appear to be any ruly portable and reliable way to find that out! My suggestion is therefore to just open the file, read it a character at a timc, counting the number of charucters but not trying to save them, and close it again. Rcading the file twice (once only to find its sizc) is of course incfficient but will give thc desirod result (unless some other application is changing the file at the same time) using only standard and portable C functions, and coming up with a nicer way to accomplish this task is beyond the scope of this assignment. Once you have the (best estimate for) file size, you can allocate a single array for the file using nalloc, something like this: char data-alloc(size in bytes)i You can now operate on data as if it had been declared as an array of char. (Check first that alloc succeeded.) Now you can read in the contents of the file; a character at a time is probably simplest. Notice that as you do this you will get the newline characters at the ends of lines. (You might write this much of the program and check that it works before o going on.) o Once you have the whole file in memory, the objective is toort t with qsort. The sample program sorter-improvedc. has an example of using gsort. It needs four parameters: an array to sort (of elements of fixed size), a count of elements, a size for each element, and a comparison function. Your first thought may be to wonder how this can work, since text strings aren't of fixed size. But we can play a trick The idea will be to build an array of pointers pointing to starts of lines, sort the pointers so the first one points to the first line to print, ctc., and use them to print the lines in order. (lf you think you know at this point how to proceed, you could try doing so, and then come back and read the rest of this description.) So the next step is to build the array of pointers to lincs. How many do you need? Well, you could figure that out as youre reading the file into mcmory. Say you have that in a variable called H. Then you can allocate spacc for an array of pointers like this: char ** lines-malloc (sizeof (Lines 10)) + ?); The first one should point to datalOl. which you can accomplish like this: Then the idea is to go through the rest of the characters, and make lines1] point to the character after the first newline, ines2) point to the character after the second newline, etc o Once you get this array built, you can check it by printing the file contents out again using the array of pointers; for example, to print the first line you can write printtineato]): (You'll need this code anyway, so might as well write it now and check that it works. You may get a surprise when you first run it, as a result of which you may decide you need to do more processing of your data array. More-explicit hint in a footnote2 so you can at least try to figure it out for yourself first.) o Now the missing piece of the puzzle is to use gsort to actually sort the lines before printing them. Its parameters were described carlier, the only one you don't yet have is the comparison function. It can look a lot like the one in the sample program; all that's different is that you're sorting pointers-to-strings rather than integers. You will probably want to use the C library function strcup for the actual comparison. Read its man page to find out what it docs and what parameters it takes.Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// Function to display sorted data
void displayData(char** stringData, int length)
{
int counter = 0;
// Loops till number of rows in the matrix
for (counter = 0; counter < length; counter++)
// Displays matrix contents
printf("%s ", stringData[counter]);
}// End of function
// Function make partition
int Partition(char** stringData, int m, int length)
{
char *tempData;
char *currentData = stringData[length];
int c = m - 1;
int counter = 0;
// Loops till number of rows in the matrix
for(counter = m; counter <= length; counter++)
{
// Checks if the string at counter index position is less than or equals to current string
if(strcmp(stringData[counter], currentData) <= 0)
{
// Increase the c position by one
c = c + 1;
// Swapping process
tempData = stringData[c];
stringData[c] = stringData[counter];
stringData[counter] = tempData;
}// End of if condition
}// End of for loop
// Checks if c value is less than length
if(c < length)
// Returns c value
return c;
// Otherwise returns c minus one value
else
return c - 1;
}// End of function
// Recursive function to perform quick sort
void QuickSort(char** stringData, int m, int length)
{
// Checks if m value is less than r value
if(m < length)
{
// Call the function for partition and stores the return position
int pos = Partition(stringData, m, length);
// Recursively calls from m to position
QuickSort(stringData, m, pos);
// Recursively calls from position plus one to length
QuickSort(stringData, pos + 1, length);
}// End of if condition
}// End of function
// main function definition
int main(int argc, char *argv[])
{
// Declares a pointer to pointer of type character for character matrix
char **stringData = NULL;
// File pointer declared
FILE *fileRead;
// Loops variable
int i;
// To store temporary data read from file
char temp[20];
// Record counter
int counter = 0;
// Opens the file passed as command line argument for reading and checks whether it can be opened or not
if ((fileRead = fopen(argv[1], "r")) == NULL)
{
// If unable to open shows error message
printf("Error! in opening file for reading %s", argv[1]);
// Program exits if the file pointer returns NULL.
exit(1);
}// End of if condition
// Loops till end of file to count number or records
while(!feof(fileRead))
{
// Reads the data
fscanf(fileRead,"%s", temp);
// Increase the record counter by one
counter++;
}// End of while loop
// Dynamically allocates memory for number of rows to the character matrix of size record counter
stringData = (char**) malloc(counter * sizeof(char*));
// Loops till record counter for number of rows
for(i = 0; i < counter; i++)
// Dynamically allocates for number of columns to the character matrix of size 30
stringData[i] = (char*) malloc(sizeof(char) * 30);
// Reset the record counter to zero
counter = 0;
// Close the file
fclose(fileRead);
// Reopens the file for reading data
fileRead = fopen(argv[1], "r");
// Loops till end of file to read data and store in matrix
while(!feof(fileRead))
{
// Reads data from file and stores at counter position of the matrix
fscanf(fileRead,"%s", stringData[counter]);
// Increase the record counter by one
counter++;
}// End of while condition
// Closes the file
fclose(fileRead);
printf(" Before Sorting: ");
// Calls the function to display sorted data
displayData(stringData, counter);
// Calls the function to perform quick sort
QuickSort(stringData, 0, counter - 1);
printf(" After Sorting: ");
// Calls the function to display sorted data
displayData(stringData, counter);
// Release the memory
free(stringData);
return 0;
}// End of main function
Sample Output:
Before Sorting:
Pyari
Mohan
Sahu
Amit
Sasmita
Kumari
Panda
Binod
Ram
Kumar
Kar
Anita
After Sorting:
Amit
Anita
Binod
Kar
Kumar
Kumari
Mohan
Panda
Pyari
Ram
Sahu
Sasmita
QuickSortData.txt file conttents
Pyari
Mohan
Sahu
Amit
Sasmita
Kumari
Panda
Binod
Ram
Kumar
Kar
Anita
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.