1

I would like to ask if anyone know why when i put the code like this:

            char buff[100];
            FILE *pf = popen("/bin/file ola.png", "w");
            fscanf(pf, "%s", buff);
            pclose(pf);

It prints: ola.png: Zip archive data, at least v1.0 to extract

And if i put:

            char buff[100];
            FILE *pf = popen("/bin/file ola.png", "r");
            fscanf(pf, "%s", buff);
            pclose(pf);
            printf("%s", buff);

it prints just: ola.png:

I would like it to save the entire phrase on the buffer, not just ola.png:

Thank you!

Andre
  • 11
  • 1

1 Answers1

2

save the entire phrase on the buffer

The "%s" in char buff[100]; ... fscanf(pf, "%s", buff); directs code1 to:

  1. Read and skip any leading white-spaces.

  2. Read and save 1 or more non-white-spaces into buff - possibly overrunning buff.

  3. Continue until reading a white-space (like '\n'), put it back into pf and then append a '\0' to buff.

This does not read an entire line of input. More like one "word". It is also worse than gets lacking a width limit like "%99s".

Instead use fgets() to read a line into a string. Result includes any '\n'.

if (fgets(buff, sizeof buff, pf)) Success();

1 some details omitted for brevity. C17dr spec details.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256