0

Here I want to create tar file of bin folder only . My main.c code has location i.e. /home/amit/practice/datafill/main.c. datafill directory contains folders like bin, conf, config, data,lib.

There is one link system("cd <path>") in a C program But it doesn't solve my problem . with the use of combining 2 commands with && operator it is creating bin.tar from bin folder only ,but when it is extracted, it is containing full path link /home/amit/practice/datafill/bin/ which is wrong .Suppose there is one file abc.txt inside bin folder . So after extraction ,abc.txt should have path as bin/abc.txt only, not /home/amit/practice/datafill/bin/abc.txt

#include<stdio.h>
#include<unistd.h>
int main(void)
{
char Cmd[256];
/*Go to specific directory && create tar file*/
sprintf(Cmd,"cd /home/amit/practice/datafill/bin/ && sudo tar -cvf bin.tar *");
system(Cmd);
return 0;
}
user3559780
  • 351
  • 1
  • 2
  • 12

1 Answers1

1

Your code creates the tar file in the bin directory, but it appears you checked an older attempt in the current directory.

This code is strange and unnatural. I would normally do something like this:

 `cd /home/amit/practice/datafill/bin/ && sudo tar -cvf - *`

which causes the tarball is written to the program's standard output. If you want to generate it to a specific path, this would be more reasonable

 `sudo sh -c '(cd /home/amit/practice/datafill/bin/ && tar -cvf - *) > bin.tar'`
Joshua
  • 40,822
  • 8
  • 72
  • 132
  • its working properly but what is meaning of tar -cvf - * part , Suppose in bin folder there is one file named abc.txt . is possible to exclude that file from bin folder while creating the tar file? .what changes need to be done in this command. ? – user3559780 Feb 09 '21 at 17:37
  • @user3559780: There are ways but I recommend abandoning the `system` API and designing the thing more robustly for such a complicated job. – Joshua Feb 09 '21 at 17:45
  • fine ,but what is meaning of tar -cvf - * part?? .because this is different than normal command for example. tar -cvf bin.tar bin – user3559780 Feb 10 '21 at 02:16
  • @user3559780: - where a file name goes means stdin/stdout. In this case stdout. So we redirect outside the cd. – Joshua Feb 10 '21 at 02:25
  • do u have any link or document where I can get more information about it ? I am searching on internet about it .but not found about it yet – user3559780 Feb 10 '21 at 02:36