I have a question about the implementation of my Quicksort on strings in a file.
This exercise requires to input the file name of the file which you want to open and it can have at most 100 items. With the function char filling(FILE* myfile), every row contained in the file is copied into an array through a while cycle which ends at the End Of File.
Then it is called the function sort(strings, start, end, leq) to sort the array of strings which, at the end of the function, will be copied into a new file called sorted_myfile.
My question is: how can I test if my program works with files?
In the function char filling the declaration leq_fn leq refers to the declaration of a pointer to function typedef bool(* leq_fn )(char *, char *) which is included in the function of the quicksort. I hope I gave you all the information you need to help me. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "quicksort.h"
#define MAX_LENGTH 100
#define EXTRA_LENGTH 101
#define LENGTH_STRING 255
char filling(FILE *myfile);
char *strings[MAX_LENGTH]; //Array of at most 100 items
char filling(FILE *myfile){
char *row;
char new_filename[LENGTH_STRING];
FILE* sorted_myfile;
int i=0, start=0, end=MAX_LENGTH-1;
bool res_cmplen, res_cmpalpha, res_cmpalpha_nocase;
FILE *sorted_myfile;
while(i<=EOF){
if(i==EXTRA_LENGTH){
printf("The file has more than 100 items\n");
}else{
row = calloc(LENGTH_STRING, sizeof(char));
fgets(row, LENGTH_STRING, myfile);
strings[i]=row;
i++;
free(row);
}
}
leq_fn leq;
leq = cmp_len;
res_cmplen = (*leq)("hello", "bye");
leq = cmp_alpha;
res_cmpalpha = (*leq)("HELLO", "bye");
leq = cmp_alpha_nocase;
res_cmpalpha_nocase = (*leq)("hello", "BYE");
sort(strings, start, end, leq);
scanf("%s", new_filename);
sorted_myfile = fopen(new_filename, "w");
for(i=0;i<end;i++){
fputs(strings[i], sorted_myfile);
}
return 0;
}
int main(void) {
char filename[LENGTH_STRING];
FILE *myfile;
printf("What is the file name?\n");
scanf("%s", filename);
myfile = fopen(filename, "r");
if(ferror(myfile)!=0){
printf("The file doesn't exist\n");
}else{
filling(myfile);
}
return 0;
}
fillingfunction, the loop will not be iterated even once. The macroEOFis usually defined as-1, and0 <= -1is never true. Also, to check if the file opened correctly, you need to check if the returned pointer isNULLor not, not callferror, and there might also be many other problems besides the file not existing.calloc, copy the pointer (but not what the pointer points to) and then free the just allocated memory, leaving the pointer to point to unallocated memory. Using that pointer in any way leads to undefined behavior.iis less thanMAX_LENGTH(the size of thestringsarray). And also check whatfgetsreturn, so you don't iterate once you reach the end of the file.