How to retrieve a file/folder's properties in C, particularly in Linux?
I need info about date created, last modified, isDirectory or isFile, permission, ownership and size.
Thanks.
How to retrieve a file/folder's properties in C, particularly in Linux?
I need info about date created, last modified, isDirectory or isFile, permission, ownership and size.
Thanks.
You most likely need the stat()
function.
Example:
struct stat attr;
stat("/home/crazyfffan/foo.txt", &attr);
printf("Size: %u\n", (unsigned)attr.st_size);
printf("Permissions: %o\n", (int)attr.st_mode & 07777);
printf("Is directory? %d\n", attr.st_mode & ST_ISDIR);
etc.
Use the stat
system call. man 2 stat
.
You'll get a structure that includes what you're looking for.
From the man page:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
Look over the example in the man page for details about determining file type using the st_mode
field; here's how to check isDirectory
/isFile
using the POSIX macros:
isDirectory = S_ISDIR(statBuf.st_mode);
isFile = S_ISREG(statBuf.st_mode);
struct stat file_stats;
fd = open(filename, O_RDONLY);
if (fd == -1) {
exit(-1);
}
if (fstat(fd, &file_stats) < 0) {
exit(-1);
}
if (S_ISDIR(file_stats.st_mode)) {
printf("It is dir\n");
} else {
snprintf(msg, PATH_MAX, "%lld, %ld, %o, %d, %d, %d, %lld, %ld, %ld, %ld, %ld, %ld,
%ld\n",
file_stats.st_dev,
file_stats.st_ino,
file_stats.st_mode,
file_stats.st_nlink,
file_stats.st_uid,
file_stats.st_gid,
file_stats.st_rdev,
file_stats.st_size,
file_stats.st_blksize,
file_stats.st_blocks,
file_stats.st_atime,
file_stats.st_mtime,
file_stats.st_ctime);
}