Francesco
Francesco

Reputation: 650

printf() after popen(): strange behaviour

I don't understand the behaviour of using printf() after popen(). I have a folder with these 3 files:

  1. middle.txt
  2. test.app
  3. test.c

test.c is the source code of test.app:

test.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char **argv)
{
    FILE *fpipe;
    char *command = "ls";
    char c = 0;
    char output[1000];

    fpipe = popen(command, "r");

    if (fpipe == 0)
    {
        perror("popen() error");
        exit(1);
    }

    while (fread(&c, sizeof c, 1, fpipe))
    {
        strncat(output, &c, 1);
    }

    pclose(fpipe);

    char *position;
    char result[9];

    position = strstr(output, "test.app");

    if (position != NULL)
    {
        memcpy(result, position + 8, sizeof(result));
        fflush(stdout);
        printf("Output string: %s", result);
        fflush(stdout);
    }

    return 0;
}

When I run test.app I obtain this ouput:

Output string: test.app test.c

Why not this?

Output string:
test.app

EDIT

Using suggestions from the comments I modified 3 lines (position + 8 is a mistake from my original source code) with these:

char output[1000] = {0};
char result[9] = {0};
memcpy(result, position, sizeof(result));

but now this is the output:

Output string: test.app
middle.txt
test.app
test.c

Upvotes: 2

Views: 205

Answers (1)

Francesco
Francesco

Reputation: 650

I modified 3 lines (by opening post) with these:

char output[1000] = {0};
char result[9] = {0};
memcpy(result, position, sizeof(result) - 1);

and now this is the output:

Output string: test.app

1 Byte presents in output was responsible of this strange behaviour. We have to pay attention with the copied size, printed buffer must be a null-terminated string

Upvotes: 2

Related Questions