Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include <dirent.h>
- #include <string.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <fcntl.h>
- #define BUFF_SIZE (1 << 10)
- void printNthChar(const char path[], int n) {
- int fd = open(path, O_RDONLY);
- if (fd < 0) {
- perror("");
- exit(1);
- }
- char buffer[BUFF_SIZE];
- int totalRead = 0, bytesRead, ok = 0;
- while ((bytesRead = read(fd, buffer, BUFF_SIZE)) > 0) {
- for (ssize_t i = 0; i < bytesRead; ++i) {
- totalRead++;
- if (totalRead == n) {
- printf("The %d-th character is: '%c'\n", n, buffer[i]);
- ok = 1;
- break;
- }
- }
- if (ok) {
- break;
- }
- }
- if (bytesRead == -1) {
- perror("");
- exit(1);
- }
- if (close(fd)) {
- perror("close");
- }
- }
- void iterateDir(const char path[], int n) {
- DIR *dir = opendir(path);
- if (dir == NULL) {
- perror("");
- exit(1);
- }
- for (struct dirent *dep; (dep = readdir(dir)) != NULL;) {
- const char *const dName = dep->d_name;
- if (!strcmp(dName, ".") || !strcmp(dName, "..")) {
- continue;
- }
- char absPath[BUFF_SIZE];
- sprintf(absPath, "%s/%s", path, dName);
- struct stat statBuff;
- if (lstat(absPath, &statBuff)) {
- perror("");
- exit(1);
- }
- const mode_t mode = statBuff.st_mode;
- if (S_ISDIR(mode)) {
- iterateDir(absPath, n);
- } else if (S_ISREG(mode)) {
- printf("%s\n", absPath);
- off_t size = statBuff.st_size;
- if (size < n) {
- puts("OUT_OF_BOUNDS!");
- } else {
- printNthChar(absPath, n);
- }
- }
- }
- if (closedir(dir) != 0) {
- perror("closedir");
- }
- }
- int main(int argc, char *argv[]) {
- if (argc != 3) {
- fprintf(stderr, "Wrong usage!\n");
- exit(1);
- }
- int n = atoi(argv[2]);
- iterateDir(argv[1], n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement