Write a program that takes a single directory as an argument, and iterates throu
ID: 3550796 • Letter: W
Question
Write a program that takes a single directory as an argument, and iterates through all the normal files in the directory, and concatenate them to standard out.
Takes only one argument, the directory to cat.
Checks to make sure the argument passed in is actually a directory.
If the wrong number of arguments are given, or the argument given is not a directory, then the program quits with an error message.
If a valid directory is given, then open the directory, and examine every file in it.
For each regular file in the directory (hint S_ISREG), you dump it's contents to standard output.
Continue on, until all regular files in the directory have been output.
7. Output the files in the order you find them in the directory.
Explanation / Answer
Sourcecode: http://pastebin.com/sBAp3Lmb
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#define MAX_FILENAME 500
int main(int c, char *v[])
{
DIR *pDir;
struct dirent *pDirent;
struct stat statbuff;
char curr_filepath[MAX_FILENAME];//to store file path
FILE *fp;
char buffer;
if(c != 2)
{
printf("Invalid arguments. Usage: progname <dirname> ");
return 1;
}
/*Open Current Directory*/
pDir = opendir(v[1]);
if(pDir == NULL)
{
printf("Error: Cannot open directory '%s' ",v[1]);
return 1;
}
/*Read all items in directory*/
while((pDirent = readdir(pDir))!=NULL)
{
/*Skips . and ..*/
if( strcmp(pDirent->d_name, ".") == 0 || strcmp(pDirent->d_name, "..") == 0)
continue;
/*constructing the file path of the cuurent file*/
strcpy(curr_filepath,v[1]); //copying directory
strcat(curr_filepath,"/"); //appending seperator / (for unix systems)
strcat(curr_filepath,pDirent->d_name); //appending filename
/*Report error if cannot get stats
stat returns 0 on success and -1 on failure */
if(stat(curr_filepath, &statbuff))
{
printf("Error in getting stats of %s ",pDirent->d_name);
continue;
}
/*Check if this is a regular file*/
if (S_ISREG(statbuff.st_mode))
{
/*Opening file for reading*/
fp = fopen(curr_filepath,"r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);//printing to stdout
}
fclose(fp);//closing file
}
}
closedir(pDir);//closing directory
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.