I
I
Irina2020-02-19 13:50:01
C++ / C#
Irina, 2020-02-19 13:50:01

How do I properly concatenate three strings and make a system call?

Good afternoon. There is this code in C:

char filenames[1000];
        memset(filenames, 0, 1000);
        printf("Enter filenames:\n");
        read(0, filenames, 1000);
        printf(filenames);
        char* part1 = "file ";
        char* part2 = "| grep 'C source' | wc -1";
        char* result = malloc(strlen(part1) + strlen(filenames) + strlen(part2) + 1);
        memset(result, 0, strlen(part1) + strlen(filenames) + strlen(part2) + 1);
        memcpy(result, part1, strlen(part1));
        memcpy(result, filenames, strlen(filenames));
        memcpy(result, part2, strlen(part2));
        printf(result);
        system(result);

The task is as follows: you need to get file names separated by spaces from the user. Next, I want to embed these names in the query "file | grep 'C source' | wc -1", and then make a call to this command using system. Unfortunately, it doesn't work for me. I tried to use strcat but it doesn't work either.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2020-02-19
@SirenaProgrammer

When doing memcpy, the pointer to result must be offset by the size of the previous copied line. Now you just copy the next line, overwriting the previous copy.

memcpy(result + strlen(part1), filenames, strlen(filenames));

strcat should work fine, it does essentially the same thing.
When copying strings, it's better to use strcpy (or strncpy), it copies with a terminating 0. memcpy is designed to copy memory of arbitrary content.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question