1832978 Members
2475 Online
110048 Solutions
New Discussion

Re: command in c

 
SOLVED
Go to solution
Xiaoming Zhang
Contributor

command in c

Hi,

I am writting a c program to process dynamic created files. The files are in a specific directory and I have to delete some of them and move rest to another specific directory.

How am I going to delete and to move files in a c program?

Thanks!

Xiaoming
2 REPLIES 2
Gregory Fruth
Esteemed Contributor
Solution

Re: command in c

Use the unlink() and rename() library calls:

#include
#include

if (unlink("somefile") !=0) {
/* an error occurred */
}
if (rename("source", "dest") != 0) {
/* an error occurred */
}

Don't use unlink() on directories!!!!! Use stat() to find out if
"somefile" is a directory, a link, etc.

If "source" and "dest" are on different filesystems,
rename() will fail. Handle errno == EXDEV specially.

As always, read the man pages carefully!

Good luck!

Felix J. Liu
Advisor

Re: command in c

The quick and dirty way:

system("rm -f file1");
system("mv -f file2 dest_dir");

Try to follow the proper way given above.