I wrote a word sorting program so that if the -r
argument is present at the command line then the sorting will be done in reverse order (reverse sorting option)
I tried to store all the arguments from the command line in an array, then display them in reverse order, because I noticed that if I try to create a "for" loop for iteration (for example: for (opting = count; choosing> 0; choosing--)
), the program does not finish its execution and displays all my arguments continuously.
I set the variable "opterr = 0" so that I don't get any more errors like "invalid option -m"
The program executes -r
correctly, only when it is added several times it is considered as text, and when adding an unknown parameter next to the others the program executes further and does not stop. How can I fix this?
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int i, j, m, n, option;
char *temp;
int count = argc - 1;
int re_count = 0;
int y = -1;
char* ptrr[count];
for(i=0;i<argc;i++)
{
for(j=1;j<(argc-1-i);j++)
{
if(strcmp(argv[j],argv[j+1])>0)
{
temp=argv[j];
argv[j]=argv[j+1];
argv[j+1]=temp;
}
}
}
opterr = 0;
while ((option = getopt(argc,argv,"r"))!=-1) {
switch(option){
case'r':
for(;optind<argc;optind++){
y++;
m = strlen(argv[optind]);
ptrr[y] = (char *)calloc(count, sizeof(char)*(m+1));
strcpy(ptrr[y], argv[optind]);
re_count++;
}
int num = sizeof(ptrr) / sizeof(ptrr[0]) - (count - re_count);
for(i = num - 1; i > -1; i--) {
printf("%s ", ptrr[i]);
}
break;
case'?':
if(optopt != NULL) {
fprintf(stderr, "You have entered an unknown optional argument: -%c", optopt);
}
break;
}
printf("\n");
}
for(;optind<argc;optind++) {
printf("%s ",argv[optind]);
}
printf("\n");
return 0;
}