Need help with running the tar command using system() call in C

Hey everyone,

I've been trying to use the system(cmd) call in C to tar multiple files together.
When i do so i specify the absolute paths of the tar file as well as the files to be included in the tar file.

Eg: system("tar -cf /tmp/example.tar /mnt/john/1.xml");
system("tar -uf /tmp/example.tar /mnt/john/2.xml");
system("tar -uf /tmp/example.tar /mnt/john/3.xml");

I was expecting that upon extraction of example.tar i'd get 1.xml,2.xml and 3.xml. However upon extraction 'mnt' and 'john' directories are again created in the extraction directory and inside these reside the desired xml files.

Is there a way i can prevent these directories from being created and get only the xml files upon extraction?

Thanks.

tar always preserves paths, so the only way to do what you want is to change to the directory where the files are, and add them from there using just thier name not path/name

system("tar -cf /tmp/example.tar 1.xml");
system("tar -uf /tmp/example.tar 2.xml");
system("tar -uf /tmp/example.tar 3.xml");

so either run your C program from the directory where the files are, or set that as being the current directory before issuing the system call

Thanks Wempy !
How do i change the current directory using C ?

Does system("cd /mnt/john/"); work?
or do i use the chroot() system call ? But this would alter the system's root directory. I could change it back to / again though when my process is terminated.

Which one's preferred here?

chroot is not what you want, it changes the / path to be the named dir, so any subsequent calls will have that as their / path - not a good idea

chdir() is what you need
man 2 chdir will give you information on chdir (on a linux machine anyway)

Ahh..didn't know about this call at all.

Thanks so much man! Really appreciate it.

Make sure you check result code, also take care of error/warning that tar spits out on stderr