brace expansion in c program with system function

Viewed 344

I tried the command

cat tmp/file{1..3} > newFile

and works perfect

But when i compile and execute the following c program

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

void main() {
   char command[40];
   int num_of_points = 3;
   sprintf(command,"cat tmp/file{1..%d} > file.Ver",num_of_points);
   system(command);
}

the message

cat: tmp/file{1..3}: No such file or directory

appears

It seems like system does not make brace expansion

2 Answers

It seems like system does not make brace expansion

The problem is the shell invoked by system(), it is not Bash, but another shell which does not support brace expansion.


You can still call bash with the option -c in order to use bash with system(). For example:

system("bash -c 'echo The shell is: $SHELL'")

bash itself will run on top of the other shell (i.e.: the shell system() invokes), but the echo command will definitely run in Bash.

By applying the same principle in your code:

sprintf(command,"bash -c 'cat tmp/file{1..%d} > file.Ver'",num_of_points);

will create the proper command string you need to pass to system(), so that the command cat tmp/file{1..%d} > file.Ver is run in Bash and brace expansion is performed.

The man pages for the system command say: "system() executes a command specified in command by calling /bin/sh -c command"

So it wouldn't perform bash-like brace expansion. I suggest you build up the string of files to cat together in a loop, but watch out you don't overflow the command buffer.

Related