I am building an application which has to check a directory for new files then, for each new file, launch a new process which manipulate that file (after which the file gets deleted).
Basically the program reduces to the following:
while(1) {
DIR * directory = opendir("/example");
struct dirent * directory_data;
if(directory) {
while((directory_data = readdir(directory)) != NULL) {
if(directory_data->d_type == DT_REG) {
// Checking if that file is new and was not already manipulated, by a previous loop (stored the last loop list of files in a char array)
execute_manipulator(directory_data->d_name);
}
}
}
// With some error checking
closedir(directory);
usleep(300000); // 0.3 secs
}
The question is regarding speed. Is there a faster way to check a directory for new files than using dirent
's opendir
and readdir
? I noted out that once at 3-4 seconds the CPU usage of program is around 1% (I would like to make it faster, almost not to be noticed, if possible).
Note: I also used to store previous loop list of files in a char
array rather than storing the last higher mtime
and using stat
, to check if the file is new, because using RAM should be much faster.
Thank you!