Domanda

I am writing a c program where I am using a Shell Command to add the 3rd column values of a file. The command I am using is:

awk '{ sum += $3 } END { print sum }' filename

On the Ubuntu Terminal it works perfectly, buy my problem is when I implement it on my c program:

system("awk '{ sum += $3 } END { print sum }' "  filename);

I get the following compilation error:

error: expected `)' before ‘filename’
È stato utile?

Soluzione

In C you can concatenate two string literals, but it doesn't work with variables.

You have to concatenate using e.g. a function from the printf family:

char buffer[256];
snprintf(buffer, sizeof(buffer), "awk '{ sum += $3 } END { print sum }' %s", filename);

system(buffer);

Note, however, that if filename contains special characters like ' or , it may break the command (it's a security issue, too).

So you have to escape the filename properly.

A better alternative would be to use a function from the exec family:

execlp("awk", "awk", "{ sum += $3 } END { print sum }", filename, NULL);

execlp() takes every separate command argument in a separate function argument, thus freeing you from having to do concatenations and escaping.

The first argument is the program to execute. The second one is the first argument (usually, this is the program's name). Other program arguments follow. NULL indicates the end of the arguments.

Altri suggerimenti

Normally if exec family function such as execl ,execlp,execle are run as another process. Because of if you are to use such function You have to create new process using fork() system call and using dup2(file duplicator) system call you can handle as you wish .Here is simple sample c code which can do what you expect :)

   #include<unistd.h>
   #include<stdio.h>
   #include <fcntl.h>             

   int main() {

int p;
int fd[2];
char buf[4];

pipe(fd);
p=fork();
if (p) {
    close(fd[0]);
    dup2(fd[1],1);
    execlp("awk","awk","{sum+=$3} END {print sum}","input",NULL);
} else {
    close(fd[1]);
    read(fd[0],buf,4);
    int sum;
    sscanf(buf, "%d", &sum);
    printf("sum is :%d\n",sum);
}

return 0;

}

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top