I want to clean all files in a directory on Linux (not deleteing them, only clear their content)
I need to do it in C.
I want to clean all files in a directory on Linux (not deleteing them, only clear their content)
I need to do it in C.
Actually, you really don't need to do it in C. UNIX includes tools that can just about do any task that you want.
find . -type f -exec cp /dev/null {} ';'
That particular snippet above will find all files under the current directory and attempt to copy the null device to it, effectively truncating the file to 0 bytes.
You can change the starting (top level) directory, restrict names (with -name '*.jpg'
for example) and even restrict it to the current directory (no subdirectories) with -maxdepth 0
.
There are many other options with find
that you can discover by entering man find
into your command line shell. Just don't enter it into Google, you may get more than you bargained for :-)
If the need to use C is an absolutely non-negotiable one, I would still do it this way but with:
system ("find . -type f -exec cp /dev/null {} ';'");
I'm not keen on re-writing software that someone's already put a bucketload of effort into providing for free :-)
If, after my advice, you still want to do it the hard way, you need to look into opendir
, readdir
and closedir
for processing directories, then just use fopen
in write mode followed by fclose
on each candidate file.
If you want to navigate whole directory structures rather than just the current directory, you'll have to detect directories from readdir
and probably recurse through them.
scandir
to list them, then for every file:fopen(, w+)
fstat
to get the sizefwrite
the whole file with zeroes? (this is what you mean by clear?)fclose
A nice shell variant would be: shred -z directory/*