Mr.Sir
Mr.Sir

Reputation: 3

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.

Upvotes: 0

Views: 1331

Answers (3)

dolphy
dolphy

Reputation: 6498

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.

Upvotes: 1

pmg
pmg

Reputation: 108978

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 */
}

Upvotes: 5

Prof. Falken
Prof. Falken

Reputation: 24867

I don't know for sure. Is ourList big enough? You should also really, really check the return value of fgets().

Upvotes: 1

Related Questions