Search code examples
cstringprintffgets

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.


Solution

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