I need to fill a buffer space with file descriptors of files from a defined source directory. So I have the startup code:
int main(int argc, char* argv[])
{
DIR *src=opendir(argv[1]);
struct dirent *DirEntry;
char* buffer[200];
do {
DirEntry = readdir(src);
if(DirEntry != NULL) {
//put file into buffer
}
}while(DirEntry!=NULL);
}
How do I complete this loop to place all file descriptors of a given directory into the array called ‘buffer’? Should I use an object of DirEntry like DirEntry->d_name to return a file descriptor that I then put into the array?
If you need to move files from a source directory to a destination directory, you are going to need file names much more than you need file descriptors. With the names, you can open and close descriptors whenever needed; without the names, you can’t create the files in the target directory sensibly. However, we can handle file descriptors too.
So, assuming you have
strdup(), you might use:And in your loop:
where
bufferis an array ofFileandiis a convenient integer:You should also add a condition to the main condition to ensure no overflow (or replace the fixed size buffer with a dynamically allocated one):
You could sensibly break the loop if
ireaches the limit. You could test whether the name represents a file (as opposed to FIFO, block device, character device, socket, symlink, directory, …); you’d probably usestat()orlstat()for that. The file descriptor would be negative (-1) if theopen()call failed. You might conserve entries by not incrementingiif the memory allocation fails, but it is probably not worth worrying about. If the memory allocation for a file name fails, there isn’t going to be much else that works.