Good time of day, everyone!
In my program, I have encountered the necessity of normalizing strings so I could pass them to the execvp() method.
I want my routine to proceed the string in the following way: it must remove all the spaces, tabulations and newline characters that precede and follow the string; if the substring is put in the quotation marks, the method must remove them and leave their content as is. The last character is set to null.
That means that I want the function to return the same string for all of the following input cases:
If I simply print out the results and their lengths by calling printf(), everything seems all right (they coincide). But the issue is, if I invoke execvp(), it works only for the two first strings (in the second one ls is followed by tabs and spaces) and throws "No such file or directory" for other cases.
This is just a sketch but nonetheless:
Code:
#define TRUE 1
#define FALSE 0
void set_format(char *str) {
int i, flag; // flag means we encountered quatation marks
printf("\nBefore formatting\n|%s|\n", str);
for (i = 0, flag = TRUE;
strchr(" \t\n\"", str[i]) != NULL;
i++ ) {
if (str[i]=='\"') {
flag = FALSE;
break;
}
}
if (flag) str+=i;
else str+=i+1;
for (i = strlen(str)-1;
strchr(" \t\n\"", str[i])!=NULL;
i-- ) {
if (str[i]=='\"') {
if (!flag) break;
else puts("Invalid input");
}
}
str[i]=(char)NULL;
printf("\nAfter formatting\n|%s|\nSize: %d\n", str, strlen(str));
}
I'm probably missing something obvious...
Thanks in advance!