Created
September 26, 2017 06:50
-
-
Save ilansmith/2a134f54fac827c0668ca142316e1272 to your computer and use it in GitHub Desktop.
An example of how to manipulate a directory entry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <dirent.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
static int path_scan(char *path) | |
{ | |
DIR *d; | |
struct dirent *ent; | |
if (!(d = opendir(path))) | |
return -1; | |
while ((ent = readdir(d))) { | |
char name[256]; | |
struct stat sbuf; | |
FILE *f; | |
int c = 0; | |
sprintf(name, "%s/%s", path, ent->d_name); | |
if (stat(name, &sbuf)) { | |
printf("unable to stat %s... continuing\n", name); | |
continue; | |
} | |
if (S_ISDIR(sbuf.st_mode)) { | |
printf("%s is a directory... continuing\n", name); | |
continue; | |
} | |
if (S_ISCHR(sbuf.st_mode)) { | |
printf("%s is a character device... continuing\n", | |
name); | |
continue; | |
} | |
if (S_ISBLK(sbuf.st_mode)) { | |
printf("%s is a block device... continuing\n", name); | |
continue; | |
} | |
if (S_ISFIFO(sbuf.st_mode)) { | |
printf("%s is a fifo device... continuing\n", name); | |
continue; | |
} | |
if (S_ISLNK(sbuf.st_mode)) { | |
printf("%s is a symbolic link... continuing\n", name); | |
continue; | |
} | |
if (S_ISSOCK(sbuf.st_mode)) { | |
printf("%s is a socket... continuing\n", name); | |
continue; | |
} | |
if (!(S_ISREG(sbuf.st_mode))) { | |
printf("%s is not a regular file... continuing\n", | |
name); | |
continue; | |
} | |
if (!(f = fopen(name, "r"))) { | |
printf("could not open file %s/%s\n", path, name); | |
continue; | |
} | |
if (fread(&c, sizeof(char), 1, f) != 1) { | |
printf("could not read a character from %s\n", name); | |
fclose(f); | |
continue; | |
} | |
fclose(f); | |
printf("first character in %s is: %d ", name, c); | |
if (20 <= c && c <=126) | |
printf("('%c')", (char)c); | |
else | |
printf("(N/A)"); | |
printf("\n"); | |
} | |
return closedir(d); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc !=2) { | |
printf("usage: path <path_name>\n"); | |
return -1; | |
} | |
return path_scan(argv[1]); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment