In this exrecie I get an input and output files. the input file contains a number and then a strings of length no longer than 10, I need to sort them and output them in the output file. I defined a char** arrStr
which contains all strings of size at most 10.
I'm trying to understand if the following code would work (for some reason I can't run it on Eclipse) my main concern is about copying the strings correctly and not losing the information. I put a note "is this ok?" next to the statement which concerns me the most, and I'd appreciate any other corrections.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
int comp(const void* p1, const void* p2) {
return strcmp((char*)p1, (char*) p2);
}
int main(int argc, char** argv) {
FILE* fin;
FILE* fout;
int N;
char** arrStr;
char str[11];
int i;
if (argc!=3) {
printf("Please enter the program's name and two paths");
assert(0);
}
fin=fopen(argv[1], "r");
if (fin==NULL) {
printf("path 1 is not valid");
assert(0);
}
fout=fopen(argv[2], "w");
if (fout==NULL) {
printf("path for file 2 is not valid");
fclose(fin);
assert(0);
}
fscanf(fin, "%d", &N);
arrStr=(char**)calloc(N, sizeof(char)*11);
for (i=0; i<N; i++) {
fscanf(fin, "%s", str);
strcpy(arrStr[i], str); /*is it ok?*/
}
qsort(arrStr, N, sizeof(char)*11, comp);
for (i=0; i<N; i++) {
if (i==N-1)
fprintf(fout, "%s", arrStr[i]);
else
fprintf(fout, "%s,", arrStr[i]);
}
fclose(fin);
free(arrStr);
fclose(fout);
return 1;
}