c - Read first line from file and access this path -
i'm writing code reads first line file, line includes path directory. list_dir()
function enter subfolders.. checked list_dir()
, it's works great when i'm sending path manually - example: list_dir ("/home/desktop/example");
here code:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <dirent.h> #include <limits.h> static void list_dir (const char *dirpath) { // open directory in dir_name dir *d; d = opendir (dirpath); /* check opened. */ printf("%s",dirpath); if (!d) { printf ("cannot open directory\n"); exit (1); } while (1) { struct dirent * entry; const char * d_name; /* "readdir" gets subsequent entries "d". */ entry = readdir (d); /* if there no more entries in directory */ if (!entry) { break; } /* print name of file , directory. */ d_name = entry->d_name; printf ("%s/%s\n", dirpath, d_name); if (entry->d_type & dt_dir) { /* check directory not "d" or d's parent. */ if (strcmp (d_name, "..") != 0 && strcmp (d_name, ".") != 0) { int path_length; char path[path_max]; path_length = snprintf (path, path_max,"%s/%s", dirpath, d_name); printf ("%s\n", path); if (path_length >= path_max) { fprintf (stderr, "path length has got long.\n"); exit (exit_failure); } /* recursively call "list_dir" new path. */ list_dir(path); } } } /* after going through entries, close directory. */ if (closedir (d)) { printf ("cannot close directory"); exit (1); } } void main(int argc, char *argv[]) { //configuration file path char* dirpath = argv[1]; file *f1 = fopen(dirpath, "r"); if (f1 == null) { printf("cannot open file reading"); exit(1); } char *line = null; size_t len = 0; ssize_t read; while ((read = getline(&line, &len, f1)) != -1) { break; } list_dir (line); fclose (f1); free(line); }
example txt file:
/home/desktop/example/ bla bla bla bla bla bla
as understand, problem when i'm sending path main()
function, list_dir()
can't open path , "cannot open directory"
error. help?
as commenters above said there newline @ end of dirpath
, that's why cannot open directory
, add strtok(dirpath, "\n");
before opendir
rid of trailing newline.
also note including headers more once , main should return int.
Comments
Post a Comment