Why does fgets return a bad string?
I don't know how else to put it, but I know I'm doing something wrong.
char *temp2= "/shares/mJim";
char ourList[1024];
fgets(ourList, 1024, modified)
sprintf(sysString, "grep -c %s %s", ourList, temp2);
Now fgets does its job, but when I try to form this string with sprintf I get grep -c Lanuncher.ini
and the rest is missing. Now here is the kicker, if I reverse the order like this:
sprintf(sysString, "grep -c %s %s", temp2, ourList);
The result will be what I want, but and invalid search for grep: grep -c /shares/mJim Lanucher.ini
Also if I do this:
sprintf(sysString, "grep -c %s %s", temp2, temp2);
It creates the expected string (开发者_如何学编程grep -c /shares/mJim /shares/mJim
). Does anyone know what is going on?
Well for input its a simple text file that is a single column list:
Launcher.ini
bits.exe
etc....
The garbage in this case is the unusually short string that I mentioned. When I print out what ourList has it returns Launcher.ini.
fgets
includes a trailing '\n'
. You probably want to remove it before building sysString ...
fgets(ourList, sizeof ourList, modified);
size_t ourListlen = strlen(ourList);
if (ourListlen && (ourList[ourListlen - 1] == '\n')) {
ourList[--ourListlen] = 0; /* remove trailing '\n' and update ourListlen */
}
I don't know for sure. Is ourList big enough? You should also really, really check the return value of fgets().
If the line you're reading from the modified
FILE stream contains a newline, that newline will be included in the returned character string. Chances are, you have:
"Launcher.ini\n"
Strip the newline, and you should be good to go.
精彩评论