Last active
August 17, 2023 08:29
-
-
Save AbrahamAriel/71749045350c9a4ade7541e8921819d3 to your computer and use it in GitHub Desktop.
(2017) Lab 7, Assignment 2: "Write a program that takes a string as an argument and return all the files that begins with that name in the current directory and its sub directories. For example > ./a.out foo will return all file names that begins with foo."
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 <stdio.h> | |
#include <dirent.h> | |
#include <string.h> | |
#include <limits.h> | |
void listFiles(char* path, char* str) { | |
DIR *dr = opendir(path); | |
if(dr != NULL) { | |
struct dirent *de; | |
while((de = readdir(dr)) != NULL) { | |
char *name = de->d_name; // Get the name of the file/folder | |
if(strstr(name, str)) { // Check if name starts with the given string | |
printf("%s/%s\n", path, name); // Yes, print the full path | |
} | |
if(de->d_type == DT_DIR) { // If it's also a folder | |
if(strcmp(name, "..") != 0 && strcmp(name, ".") != 0) { // Make sure they're not the current directory itself or its parent directory | |
char npath[PATH_MAX]; // Get the maximum limit for a path from limits.h and create a new string with that limit | |
sprintf(npath, "%s/%s", path, name); // Contstruct a new string based on the new path to the next folder | |
listFiles(npath, str); // Repeat the function with the new path | |
} | |
} | |
} | |
closedir(dr); | |
} | |
} | |
int main(int argc, char* argv[]) { | |
if(argc != 2) { // Must take two arguments | |
printf("Usage: %s foo\n", argv[0]); | |
return 1; | |
} | |
listFiles(".", argv[1]); // Start listing files from the current directory with the matching string | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment