Reputation: 271
I am trying to use system
command in a C code where i want to execute gzip -r command to convert a .txt file to .txt.gz.Now the name of the file to be converted is stored in a pointer and as per documentation provided at this link, we need to copy the whole command of gzip like this to a string
char gzip[100];
strcpy(gzip,"gzip -r /home/abc/xyz/pqr.txt");
now i have a problem here, name of file pqr.txt is stored in a pointer.So how can i pass that pointer to the string which is being copied in gzip and then is passed to the system command.
Here is the full code which i am using.
#include<stdio.h>
#include<stdlib.h>
int main()
{ char *ptr1= "gzip -r/home/shailendra/sampleprograms/C/output.txt"; //working
//char *ptr2 = "/home/shailendra/sampleprograms/C/output.txt"; // pointer used tyo store th name of file
//char *ptr = " gzip -r *ptr2.sstv"; //not working
int i;
char tar[50];
system(ptr1); //working
system(ptr); //not working
return 0;
}
so instead of first initializing an array and then copying the string to array and then passing to system command i passed the string to a pointer and then pass that pointer to the system command.
So my main concern is how i can pass the name of the file which is stored in some pointer to the string, so that it is processed by system
command
Upvotes: 0
Views: 470
Reputation: 15954
#include<stdio.h>
#include<stdlib.h>
int
main(void)
{
const char *file = "/home/shailendra/sampleprograms/C/output.txt";
char buf[500];
if (snprintf(buf, sizeof buf, "gzip -r '%s'", file) >= sizeof buf) {
/* command could not be composed, too long */
} else {
system(buf);
}
return 0;
}
Upvotes: 0
Reputation: 33273
Simply combine the two into one string. sprintf
can help you:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *ptr2 = "/home/shailendra/sampleprograms/C/output.txt"; // pointer used tyo store th name of file
char *ptr = " gzip -r '%s'";
int i;
char buf[500];
sprintf(buf, ptr, ptr2);
system(buf); //working
return 0;
}
Upvotes: 1