Socratic Challenge
[Images demonstrtaing the challenge are included but not described in text.]
Problems Encountered During Learning and Solutions via GPT
[Images showing GPT-assisted problem solving are included.]
Practical Application of stat and opendir/readdir
[Images showing the practice with stat, opendir, readdir are included.]
Code Practice
Using the stat Structure
#include <stdio.h>
#include <sys/stat.h>
int main() {
struct stat fileStat;
// Retrieving file attributes
if (stat("myfile.txt", &fileStat) == 0) {
printf("File Size: %ld bytes\n", fileStat.st_size);
printf("Number of Links: %ld\n", fileStat.st_nlink);
printf("File Inode: %ld\n", fileStat.st_ino);
printf("Owner UID: %d\n", fileStat.st_uid);
printf("Owner GID: %d\n", fileStat.st_gid);
printf("File Type and Mode: %o\n", fileStat.st_mode);
printf("Last Access Time: %ld\n", fileStat.st_atime);
printf("Last Modification Time: %ld\n", fileStat.st_mtime);
printf("Last Status Change Time: %ld\n", fileStat.st_ctime);
} else {
perror("stat");
}
return 0;
}
Retrieving File Inode Number
#include <stdio.h>
#include <sys/stat.h>
int main() {
struct stat fileStat;
// Retrieving file attributes
if (stat("myfile.txt", &fileStat) == 0) {
printf("File Inode: %ld\n", fileStat.st_ino);
} else {
perror("stat");
}
return 0;
}
Using opendir and readdir
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("/home/yuanyi/study");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir))) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
Example: redalink for Symbolic Links
#include <stdio.h>
#include <unistd.h>
int main() {
char linkname[1024];
ssize_t len;
// Reading the target path of a symbolic link
len = readlink("mysymlink", linkname, sizeof(linkname) - 1);
if (len != -1) {
linkname[len] = '\0'; // Adding null terminator
printf("Symbolic Link Target: %s\n", linkname);
} else {
perror("readlink");
return 1;
}
return 0;
}