I am trying to count only the directories from a path, but it doesn't work. So, i don't want to number both files and directories, i want only the directories. Could you help me, please?
The code:
int listdir(char *dir) {
struct dirent *dp;
struct stat s;
DIR *fd;
int count = 0;
if ((fd = opendir(dir)) == NULL) {
fprintf(stderr, "listdir: can't open %s\n", dir);
}
while ((dp = readdir(fd)) != NULL) {
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode))
count++;
}
closedir(fd);
return count;
}
your stat() call will fail, since you are not in the correct directory. This you can solve by either changing the current directory, or generate full paths and give to stat as argument.
Some Unixes, you can optimize away the stat call by looking at struct dirent, the d_type field
int listdir(char *dir) {
struct dirent *dp;
struct stat s;
DIR *fd;
int count = 0;
if ((fd = opendir(dir)) == NULL) {
fprintf(stderr, "listdir: can't open %s\n", dir);
}
chdir (dir); /* needed for stat to work */
while ((dp = readdir(fd)) != NULL) {
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue;
#ifdef _DIRENT_HAVE_D_TYPE
switch (dp->d_type)
{
case DT_UNKNOWN:
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode)) count++;
break;
case DT_DIR:
count++;
break;
}
#else
stat(dp->d_name, &s);
if (S_ISDIR(s.st_mode)) count++;
#endif
}
closedir(fd);
return count;
}
I think you want...
written in C
count the number of directoriesfrom a path.
the counting function will returns int value.
I have no idea about your environment, so it is just a example solution.
If you can use glob, it is so easy to count the number of directories. that is: main.c
#include <stdio.h>
#include <glob.h>
#include <string.h>
#define MAX_PATH 1023
int countDirectories(char* dir)
{
char path[MAX_PATH] = "";
strcat(path, dir);
strcat(path, "/*");
glob_t globbuf;
long i, count = 0;
if (glob(path, GLOB_NOSORT | GLOB_ONLYDIR, NULL, &globbuf) == 0)
{
count = globbuf.gl_pathc;
for (i = 0; i < globbuf.gl_pathc; i++)
{
count += countDirectories(globbuf.gl_pathv[i]);
}
}
globfree(&globbuf);
return count;
}
int main(int argc, char* argv[])
{
int count;
if (argc > 1)
{
count = countDirectories(argv[1]);
}
else
{
count = countDirectories(".");
}
printf("there are %d directories.\n", count);
return 0;
}
and you can try this like:
> gcc main.c -o testglob
> ./testglob /path/to/target/dir
then you'll receive output like this:
path = /path/to/target/dir/*, there are N directories
thanks.
Related
prev problem was not described well.
I need to retrieve a file name and assign that name to a variable. The only thing is that the file can have any name.
The thing that I know is the file extension and there can only be one file of this extension.
Is there any way to implement this in C?
Update #1
File extension is *.knb and target is Linux system.
#include <stdio.h>
#include <dirent.h>
#define LOG_() do{fprintf(stdout, " UNIT TESTING...\n");}while(0)
char* knbname;
void fName(void);
int main()
{
LOG_();
fName(void);
//do some more code
return 0;
}
void fName(void){
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
//find file with *.knb extension and place name into knbname
}
closedir(d);
}
I don't know how to find for a *.knb file in the fName() function and how to assign name to knbname. Any help will be appreciated
You are reinventing POSIX's glob() function. Here is an example of how to use it (see the flags in manpage for more options):
#include <glob.h>
int main(void)
{
glob_t glob_res = { 0 };
glob("*.knb", 0, NULL, &glob_res);
if (glob_res.gl_pathc == 0) puts("No match.");
else printf("First match is %s\n", glob_res.gl_pathv[0]);
globfree(&glob_res);
return 0;
}
After Andrew pointed out some major flaw in the previous design, i will make another attempt for a solution...
int hasExtension(char *filename, char *extension);
int main(void)
{
DIR *directory;
struct dirent *entry;
if(NULL == (directory = opendir(".")))
{
perror("Failed to open directory\n");
exit(1);
}
while( NULL != (entry = readdir(directory)) )
{
if(DT_REG == entry->d_type) { // Regualar files only
if(hasExtension(entry->d_name, ".knb"))
{
printf("Match - %s\n", entry->d_name);
} else {
printf("No match - %s\n", entry->d_name);
}
}
}
closedir(directory);
return 0;
}
int hasExtension(char *filename, char *extension)
{
size_t filename_len, extension_len;
if((NULL == filename) || (NULL ==extension))
return 0;
filename_len = strlen(filename);
extension_len = strlen(extension);
if(filename_len < extension_len)
return 0;
return !strcmp(filename + filename_len - extension_len, extension);
}
EDIT : Note that It's not that I can't access the memory allocated by storeContents() in main() if you think so. Program crashes during the execution of storeContents()
The program fails here :
strcpy(contents[count], dir->d_name);
printf("Stored %s(out hiddenVisible)\n", dir->d_name); // for testing
It's strcpy() not the printf(), I added it just for the reference.
The debugger(gdb) says :
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7f3cd72 in __strcpy_ssse3 () from /usr/lib/libc.so.6
I am making a program that involves the following function "storeContents"(It stores contents' names of a directory in a dynamic array). There are two issues with this function : (1) It says "Stored file_name" twice for the first file and (2) says "Segmentation fault". I can't figure out either of them. Thanks for your efforts!
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/types.h>
#include <limits.h>
static short hiddenVisible = 0;
/* Store directory's contents in **contents */
static char ** storeContents(struct dirent *dir, DIR *dirp, unsigned numOfContents);
/* Count files/directories in a directory */
static unsigned getNumOfContents(struct dirent *dir, DIR *dirp);
int main(int argc, char const *argv[])
{
char **contents;
DIR *dirp;
struct dirent *dir;
unsigned numOfContents;
dirp = opendir("/home/gaurav");
if((dir = readdir(dirp)) == NULL) {
perror("readdir");
exit(1);
}
/* Getting number of files/directories */
numOfContents = getNumOfContents(dir, dirp);
printf("There are %u files.\n", numOfContents);
/* To position again to the first entry */
rewinddir(dirp);
contents = storeContents(dir, dirp, numOfContents);
/* Print contents */
for(unsigned i = 0; i < numOfContents; ++i)
printf("%s\n", contents[i]);
closedir(dirp);
return 0;
}
char **
storeContents(struct dirent *dir, DIR *dirp, unsigned numOfContents) {
char **contents;
unsigned count = 0;
/* Allocating memory for entries */
contents = malloc(numOfContents * sizeof(*contents));
/* Allocating memory for each '*contents' */
for(unsigned i = 0; i < numOfContents; i++)
contents[i] = (char *)malloc(NAME_MAX); /* we know char is 1 byte, so no "sizeof" */
while(count < numOfContents) {
/* Ignore "." and ".." */
if(!(strcmp(dir->d_name, ".")) || !(strcmp(dir->d_name, ".."))) {
if((dir = readdir(dirp)) == NULL) {
perror("readdir");
exit(1);
}
continue;
}
if(hiddenVisible) {
strcpy(contents[count], dir->d_name);
if((dir = readdir(dirp)) == NULL) {
perror("readdir");
exit(1);
}
count++;
} else {
if(dir->d_name[0] == '.')
if((dir = readdir(dirp)) == NULL) {
perror("readdir");
exit(1);
}
else {
strcpy(contents[count], dir->d_name);
if((dir = readdir(dirp)) == NULL) {
perror("readdir");
exit(1);
}
count++;
}
}
}
return contents;
}
unsigned
getNumOfContents(struct dirent *dir, DIR *dirp) {
unsigned count = 0;
while(dir) {
if(hiddenVisible) {
/* Ignore "." and ".." */
if(!(strcmp(dir->d_name, ".")) || !(strcmp(dir->d_name, ".."))) {
if((dir = readdir(dirp)) == NULL) {
perror("readdir a");
exit(1);
}
continue;
}
count++;
if((dir = readdir(dirp)) == NULL) {
perror("readdir b");
exit(1);
}
} else {
if(dir->d_name[0] == '.') {
if((dir = readdir(dirp)) == NULL) {
perror("readdir c");
exit(1);
}
}
else {
count++;
if((dir = readdir(dirp)) == NULL) {
perror("readdir d");
exit(1);
}
}
}
}
return count;
}
contents in the function storeContents is a local copy of contents from main.
Changing it in the function does not change the variable in main.
You should return the array. Change
static void storeContents(struct dirent *dir, DIR *dirp, char **contents, unsigned numOfContents);
to
static char **storeContents(struct dirent *dir, DIR *dirp, unsigned numOfContents);
,return contents; in the function and call it like char **contents = storeContents(...);
Some bugs:
contents is a local parameter to the function, it will not get returned to main(). See Dynamic memory access only works inside function.
contents = (char **)malloc(numOfContents); is wrong, you need to allocate room for numOfContents pointers. Change this to contents = malloc(numOfContents * sizeof(*contents)).
You should check each call to readdir and make sure it doesn't return NULL.
I'm currently trying to make a c program that counts the total file size in bytes of a given directory, including the directory itself, all files within, and all files and directories in all sub-directories. Essentially, I'm being asked to program a replacement for du -b as a command.
I thought I had a working solution, but after the first directory this program thinks that all entries deeper down are directories, even when they're just regular files. This includes when I give it a directory that's one degree deeper directly, say by giving it the input ./Directory1 instead of just ..
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
int du_function(char direc[]) {
int total = 0;
char str[100];
strcpy(str, direc);
struct stat sfile;
struct dirent *de;
DIR *dr = opendir(direc);
if (dr == NULL) {
printf("Could not open directory\n");
return 0;
}
while ((de = readdir(dr)) != NULL) {
printf("%s\n", de->d_name);
stat(de->d_name, &sfile);
if (S_ISDIR(sfile.st_mode) && strcmp(de->d_name, ".") != 0 &&
strcmp(de->d_name, "..") != 0) {
strcat(str, "/");
strcat(str, de->d_name);
printf("This is a directory called %s\n", str);
total = total + du_function(str);
strcpy(str, direc);
}
if (S_ISREG(sfile.st_mode) || strcmp(de->d_name, ".") == 0) {
printf("Size in bytes = %ld\n", sfile.st_size);
total = total + sfile.st_size;
printf("The total is %d bytes so far.\n", total);
}
}
printf("The total is %d bytes.\n", total);
closedir(dr);
return total;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
char cwd[1] = ".";
du_function(cwd);
} else
du_function(argv[1]);
return 0;
}
I'm at my wit's end here and have tried a variety of solutions, but for some reason S_ISDIR must be identifying things as directories that aren't (or receiving the wrong input from me, more likely.)
char cwd[1] = "."; is too small for a string. No room the the null character.
Use [] and let the compiler determine the needed size for the string.
char cwd[] = ".";
stat() call is based on local name and not full path.
#if 0
stat(de->d_name, &sfile);
#else
char buf[500];
snprintf(buf, sizeof buf, "%s/%s", direc, de->d_name);
stat(buf, &sfile);
#endif
Similar finding in (deleted) #PSkocik
Perhaps other issues exist.
Just like you construct the path for the recursive call, you must construct the filename with the leading directory for the stat system call. Your program only works for the files in the current directory.
An effective way to fix your program is pass a large enough buffer to the recursive function and build the path and filenames incrementally in place:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
long int du_function(char path[], size_t size) {
size_t len = strlen(path);
long int total = 0;
struct stat sfile;
struct dirent *de;
DIR *dr = opendir(path);
if (dr == NULL) {
printf("Could not open directory %s\n", path);
return 0;
}
while ((de = readdir(dr)) != NULL) {
if (strcmp(de->d_name, "..") == 0)
continue;
//printf("%s\n", de->d_name);
if (snprintf(path + len, size - len, "/%s", de->d_name) > (int)(size - len)) {
path[len] = '\0';
printf("Path too long: %s/%s\n", path, de->d_name);
continue;
}
stat(path, &sfile);
if (S_ISDIR(sfile.st_mode) && strcmp(de->d_name, ".") != 0) {
//printf("This is a directory called %s\n", path);
total = total + du_function(path, size);
} else
if (S_ISREG(sfile.st_mode) || strcmp(de->d_name, ".") == 0) {
//printf("Size in bytes = %ld\n", (long)sfile.st_size);
total = total + sfile.st_size;
//printf("The total is %ld bytes so far.\n", total);
}
}
path[len] = '\0';
printf("%ld\t%s\n", total, path);
closedir(dr);
return total;
}
int main(int argc, char *argv[]) {
char path[1024] = ".";
if (argc > 1) {
strcpy(path, argv[1]);
}
du_function(path, sizeof path);
return 0;
}
I have to implement the tree command from DOS on Linux in C, so that when I run ./tree in a directory it prints it like this:
adir
bdir
cdir
d.java
edir
fdir
g.c
hdir
My current code looks like this, but it's not even terminating when I run it, but I don't know how to fix it. Please help me solve it!
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#define MAXLEN 256
char currentDir[256];
const char *pathname;
void tree(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces);
void treeHelper(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces);
int main(int argc, char* argv[]) {
DIR *dp = opendir(".");
struct dirent *dp1 = readdir(dp);
int spaces = 0;
//char currentDir[256];
getcwd(currentDir, sizeof(currentDir));
while(dp1 != NULL) {
if (strcmp(dp1->d_name, ".") == 0 || strcmp(dp1->d_name, "..") == 0) {
continue;
}
if (dp1->d_type == DT_REG) {
printf("%s\n", dp1->d_name);
}
if (dp1->d_type == DT_DIR) {
tree(dp, dp1, currentDir, spaces);
}
}
closedir(dp);
}
void tree(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces) {
int i = 0;
strcat(currentDir, "/");
strcat(currentDir, dp1->d_name);
if((chdir(currentDir)) == -1){
chdir("..");
getcwd(currentDir, sizeof(currentDir));
strcat(currentDir, "/");
strcat(currentDir, dp1->d_name);
for(i = 0; i < spaces; i++) {
printf (" ");
}
printf("%s (subdirectory)\n", dp1->d_name);
spaces++;
treeHelper(dp, dp1, currentDir, spaces);
}
else {
for(i = 0; i < spaces; i++) {
printf(" ");
}
printf("%s (subdirectory)\n", dp1->d_name);
chdir(currentDir);
spaces++;
treeHelper(dp, dp1, currentDir, spaces);
}
}
void treeHelper(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces) {
int i = 0;
while((dp1 = readdir(dp)) != NULL){
if(strcmp(dp1->d_name, ".") == 0 || strcmp(dp1->d_name, "..") == 0)
continue;
//stat(currentPath, &statbuf);
/*if(dit->d_type == 8 && argv[1] != NULL){*/
if(dp1->d_type == DT_REG){
for(i = 0; i < spaces; i++) {
printf(" ");
}
printf("%s\n", dp1->d_name);
}
/*if(dit->d_type == 4)*/
if(dp1->d_type == DT_DIR)
tree(dp, dp1, currentDir, spaces);
}
}
Thank you!
My current code looks like this, but it's not even terminating when I
run it…
struct dirent *dp1 = readdir(dp);
…
while(dp1 != NULL) {
You call readdir() only once and then have an endless loop operating on the same dirent again and again. Change that to
struct dirent *dp1;
…
while (dp1 = readdir(dp))
{
Here is a program I made this program has segmentation fault I checked it in gdb in the second last of code free(somepath); .I do not have any reason for why is this segmentation fault coming?
Some one please suggest some thing.
#include<dirent.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<stdio.h>
char *directs[20], *files[20];
int i = 0;
int j = 0;
int count = 0;
void printdir(char *);
int count_dirs(char *);
int count_files(char *);
void new_printdir(int ,int ,char *);
int main()
{
char startdir[20];
printf("Scanning user directories\n");
scanf("%s", startdir);
printdir(startdir);
}
void printdir(char *dir)
{
DIR *dp = opendir(dir);
int nDirs, nFiles, nD, nF;
nDirs = 0;
nFiles = 0;
nD = 0;
nF = 0;
if (dp) {
struct dirent *entry = 0;
struct stat statBuf;
nDirs = count_dirs(dir);
nFiles = count_files(dir);
new_printdir(nDirs,nFiles,dir);
while ((entry = readdir(dp)) != 0) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char * filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2);
if (filepath) {
sprintf(filepath, "%s/%s", dir, entry->d_name);
if (lstat(filepath, &statBuf) == 0) {
if (S_ISDIR(statBuf.st_mode)) {
printdir(filepath);
}
else {
}
}
}
free(filepath);
} //2nd while
closedir(dp);
}
else {
fprintf(stderr, "Error, cannot open directory %s\n", dir);
}
} //printdir
int count_dirs(char *dir)
{
DIR *dp = opendir(dir);
int nD;
nD = 0;
if (dp) {
struct dirent *entry = 0;
struct stat statBuf;
while ((entry = readdir(dp)) != 0) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2);
if (filepath) {
sprintf(filepath, "%s/%s", dir, entry->d_name);
if (lstat(filepath, &statBuf) != 0) {
fprintf(stderr, "File Not found? %s\n",filepath);
}
if (S_ISDIR(statBuf.st_mode)) {
nD++;
} else {
continue;
}
free(filepath);
}
}
closedir(dp);
} else {
fprintf(stderr, "Error, cannot open directory %s\n", dir);
}
return nD;
}
int count_files(char *dir)
{
DIR *dp = opendir(dir);
int nF;
nF = 0;
if (dp) {
struct dirent *entry = 0;
struct stat statBuf;
while ((entry = readdir(dp)) != 0) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char *filepath =
malloc(strlen(dir) + strlen(entry->d_name) + 2);
if (filepath) {
sprintf(filepath, "%s/%s", dir, entry->d_name);
if (lstat(filepath, &statBuf) != 0) {
fprintf(stderr, "File Not found? %s\n", filepath);
}
if (S_ISDIR(statBuf.st_mode)) {
continue;
} else {
nF++;
}
free(filepath);
}
}
closedir(dp);
} else {
fprintf(stderr, "Error, cannot open file %s\n", dir);
}
return nF;
}
void new_printdir(int nDirs,int nFiles,char *dir)
{
struct dirent **namelist;
DIR *dop;
int i, j,t,re,nD,nF;
char userd[20],*somepath;
i = scandir(dir, &namelist, 0, alphasort);
t=0;
if (i < 0)
perror ("Scandir failed to open directory I hope you understand \n");
else {
for (j = 0; j < i; j++) {
if(strcmp(".",namelist[j]->d_name)==0||strcmp("..",namelist[j]->d_name)==0)
continue;
somepath = malloc(strlen(dir)+strlen(namelist[j]->d_name)+2);
sprintf(somepath,"%s/%s",dir,namelist[j]->d_name);
dop=opendir(somepath);
if(dop)
{
nD++;
if ((nDirs-nD)<3)
{printf("%s ",namelist[j]->d_name);}
}
else {
nF++;
if ((nFiles-nF)<3)
printf("%s ",namelist[j]->d_name);
}
closedir(dop);
free(namelist[j]);
}
}
free(namelist);
free(somepath);
}
Why is this segmentation fault happening this is not clear to me.
What can I do to get rid of it?
In your code, you are not guaranteed to allocate memory and assign it to somepath (you also fail to free somepath except for the last iteration of the loop). You should put your free(somepath) statement at the end of the for-loop, and you should initialize somepath to NULL both at the very beginning of the function and at the start of each for loop to avoid similar careless errors.
You're not initializing the somepath variable - it has an undefined value unless the malloc() executes (i.e. for empty folders). You should initialize it to NULL at the place of definition.
You do not initialize somepath to 0 (NULL), but you could under some circumstances release the value. This means you release a random value - which is not a good idea.