getdents64 - Linux
Overview
getdents64
is a Linux system call used to retrieve directory entries from a file system. It is designed to efficiently handle large directories with a 64-bit data structure, enabling it to retrieve more entries per system call.
Syntax
#include <dirent.h>
int getdents64(int fd, struct dirent64 *buf, size_t nbytes);
Options/Flags
None
Parameters
fd
: File descriptor of the directory to read entries from.buf
: Pointer to a buffer where the directory entries will be stored.nbytes
: Size of the buffer in bytes.
Return Value
- On success,
getdents64
returns the number of bytes written to the buffer. - On error, it returns -1 and sets
errno
to indicate the error.
Examples
Simple Usage:
Retrieve directory entries from the current working directory:
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir(".");
struct dirent64 *entry;
while ((entry = readdir64(dir))) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
Retrieving Specific Information:
Obtain file type and size from directory entries:
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
int main() {
DIR *dir = opendir(".");
struct dirent64 *entry;
while ((entry = readdir64(dir))) {
struct stat st;
stat(entry->d_name, &st);
printf("%s: %ld bytes, type: ", entry->d_name, st.st_size);
if (S_ISREG(st.st_mode))
printf("regular file\n");
else if (S_ISDIR(st.st_mode))
printf("directory\n");
else
printf("other\n");
}
closedir(dir);
return 0;
}
Common Issues
- Insufficient Buffer Size: If the provided buffer (
buf
) is too small to hold all the directory entries,getdents64
will returnENOENT
. - Invalid File Descriptor: Using an invalid file descriptor for
fd
will result inEBADF
.
Integration
getdents64
can be used in conjunction with other Linux commands and tools, such as:
ls
: Retrieve a list of files and directories in a given directory.find
: Search for files and directories based on specific criteria.cp
andmv
: Copy or move files and directories by leveraging directory entries to identify the source and destination.
Related Commands
opendir
,readdir
,closedir
: Other system calls for directory operations.lsof
: Lists open files and sockets, which can include file descriptors for directories.