Click to See Complete Forum and Search --> : Using linux commands in C++ code
pezplaya
12-19-2004, 12:59 AM
How can I use linux commands in my c++ code?
I'm trying to write a program that will compare two files, and if the two files are the same, i want the program to delete one of the files using rm -rf or some other command.
JayMan8081
12-19-2004, 01:36 AM
I think that you can just do:
system("rm -rf");
And you can change that string to be whatever command you like.
Fryguy8
12-19-2004, 02:32 AM
diff + rm + bashscript might be more wise than writing this in c++
just a thought.
pezplaya
12-19-2004, 02:37 AM
hmm alright that is what i was looking for.
how would i go about listing a directory the user enters?
(if i store the directory the user enters as a string)
diff + rm + bashscript might be more wise than writing this in c++
just a thought.
ya, im really just fooling around with c++ right now though.
JayMan8081
12-19-2004, 03:03 AM
I think you would want to use something from dirstat.h. It allows you to perform manipulations on directories and is specific to Linux, IRC. I'm not currently in linux so I am not 100% sure on that though.
evac-q8r
12-19-2004, 04:32 AM
#include <string.h> /* You'll need this header file */
...
char *cmd, *dir;
...
sprintf(cmd,"ls -dlrt ") /* Maybe you want different options... just make sure there is a
space after options so dir doesn't become infused to
the command options */
scanf("%s", dir); /* Read input from user */
...
strcat( cmd, dir); /* Concatenate both strings */
...
system( cmd ) /* Use command as before, nothing different here */
I hope this is what you were looking for. This is mainly c though. Not any c++ here.
EVAC
truls
12-19-2004, 03:01 PM
man 3 opendir
man 3 readdir
Use opendir on the directory you want to read, then loop with readdir until there are no more directory entries. This can be improved to ignore . and .. since these are not actual files.
What you really want, if you have the money and the shelf-space, is to get the book "Advanced Programming in the UNIX Environment" by W. Richard Stevens, where all this is described in detail with sample code. This is all C code, but you can always make things easier to use by wrapping it all in C++ classes and providing iterators for the file elements.
Or you can just ask questions here, and we'll all answer them as best we can :D
tecknophreak
12-20-2004, 08:55 AM
Yeah, use the opendir and readdir to get the listings for the files/folders, then use unlink to delete the files. No need for any system calls.