I can't figure out why my string compare isn't comparing correctly. This is for C.
It's reading from a file that is set up like this:
1 - ls
2 - cd
3 - history
If I type !c it's suppose to grab the last used string that started with 'c' and run the command. Yet it never goes into the if(strcmp(())=0) line.
Part of my code is here:
char currLine[MAXINPUTLINE];
else if (isalpha(input[1])){
int count = 1;
fileRead = fopen(".simpleshell_history", "r");
while(fscanf(fileRead, "%s\n", currLine) != EOF){
printf(input+1);
printf(currLine);
if(strcmp((input+1), currLine) == 0){
printf("%s\n", currLine);
parse(currLine);
}
}
}
This is what the printf in the while loop prints, I can't figure out how to fix this and I've been stuck on it for a while. This is when I enter '!c'
c
1c
-c
lsc
2c
-c
cdc
3c
-c
historyc
4c
-c
!c!c
If
input
is the string!c
and you are looking to match that against the line2 - cd
, you will have to be careful.strcmp
will definitely not work, as it will only return success if the two strings it is comparing are exact matches.In order to test whether one string (
cd
) starts with another string (c
), you want to usestrncmp()
, which will take a limit on the number of characters to compare.Also: you will need to be careful to start comparing from the second character of
input
(skipping the!
) and from the fifth character ofcurrLine
(skipping the2 -
characters).This should get you there: