what i am trying to do is asking user to enter something in format like: cd directory. Then I store "cd" in a string and "directory" in another string. Here is my code:
void main()
{
char buf[50], cdstr[2], dirstr[50];
printf("Enter something: ");
fgets(buf, sizeof(buf), stdin);
//store cd in cdstr
strncpy(cdstr, buf, 2);
printf("cdstr: %s(test chars)\n", cdstr);
//store directory in dirstr
strncpy(dirstr, buf+3, sizeof(buf)-3);
printf("dirstr: %s(test chars)\n", dirstr);
}
The output is below with the input: cd pathname
cdstr: cdcd pathname //incorrect answer
(test chars) //an extra "\n"
dirstr: pathname //correct answer
(test chars) //an extra "\n"
That's why?
This is because after doing
strncpy(cdstr, buf, 2)
, you don't have a NULL-terminated string in thecdstr
char
array. You can fix it by changingcdstr
length to 3 and adding:cdstr[2] = '\0'
: