Assignment 1 -C program to obtain a program to a directory in a given directory – System Programming
Write a C program to obtain a program, called
ndFile, to nd a le/directory in a given directory. In particular, your program
takes an optional target directory argument and a “le name” to look for.
Synopsis: findFile [targetDirectory]
Call examples:
ndFile /usr/include/ stdio.h : search for stdio.h in /usr/include/
ndFile labs : search for labs in current directory
look in the target directory for the “le name” and, if found, prints a line with
the name found followed by either “this is a le” or “this is a directory”.
Hints:
All system calls needed to solve this problem are in the example myLs.c, that
we have seen in class.
You can use the opendir() system call to distinguish between a regular le
and a directory. If the item is a regular le, then the opendir() system call
will return NULL.
Ignore the two special directories . and ..
Answer:
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
int checkF(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
int main(int argc, char *argv[]){
DIR *dp;
struct dirent *dirp;
if (argc == 1){
printf("No filename given.\n");
return 0;
}
else
dp = opendir("./");
while ((dirp=readdir(dp)) != NULL)
if(checkF(argv[1]) == 1)
printf("Found and it is a file");
else
printf("Not found");
closedir(dp);
return 0;
}
Leave a reply