Trying to make a pwd for the c shell. This is what I found on a website and wanted to learn more about it.
I have use debugging printf statements all the way through the program already and it returns the "." instead of the actual dir name all the way through. What am I missing? Why would this be happening?
#include <dirent.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
struct stat stat_buf;
struct dirent *file_info;
ino_t itself_ino; /* holds current folder inode */
ino_t parent_ino; /* holds parent folder inode */
char Current[PATH_MAX]; /* folder name */
char Path[PATH_MAX]; /* holds the full path */
char Slash[PATH_MAX]; /* add / before the folder name */
DIR *dir;
while (1)
{
dir = opendir(".");
if(dir == NULL) {
fprintf(stderr, "cannot get current directory.\n");
exit(-1);
}
/* read the information about the current folder */
file_info = readdir(dir);
lstat(file_info->d_name, &stat_buf);
itself_ino = stat_buf.st_ino;
closedir(dir);
chdir(".."); /* go to parent directory */
dir = opendir(".");
file_info = readdir(dir);
lstat(file_info->d_name, &stat_buf);
parent_ino = stat_buf.st_ino;
if(itself_ino == parent_ino) {
/*closedir(dir);*/
break;
} else {
strcpy(Slash, "/");
strcpy(Current, file_info->d_name);
strcat(Slash, Current); /* add "/" as the first */
strcat(Slash, Path); /* charcter of the directory */
/* check the length of the pathname */
if(strlen(Slash) >= PATH_MAX) {
fprintf(stderr, "Error! Path too long!\n");
exit(0);
}
/* save the full pathname */
strcpy(Path, Slash);
}
closedir(dir);
}
/* print the full path of the current working directory */
printf("%s\n", Path);
return 0;
}
It's just realpath:
if (realpath(".", &Path) == NULL) {
// handle error
}
However maybe you aim at getcwd or get_current_dir_name.
printf("%s\n", get_current_dir_name());
Related
I'm writing a code that reads the first line from a file, where this line includes a path to directory. Then the list_dir() function would enter all subfolders..
I checked the list_dir() and it's works great when I'm sending the path manually -
For example: list_dir ("/home/Desktop/example");
Here is my 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 the directory in dir_name
DIR *d;
d = opendir (dirPath);
/* Check it was 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 from "d". */
entry = readdir (d);
/* if There are no more entries in this directory */
if (!entry) {
break;
}
/* Print the name of the file and directory. */
d_name = entry->d_name;
printf ("%s/%s\n", dirPath, d_name);
if (entry->d_type & DT_DIR) {
/* Check that the directory is 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 too long.\n");
exit (EXIT_FAILURE);
}
/* Recursively call "list_dir" with the new path. */
list_dir(path);
}
}
}
/* After going through all the entries, close the 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 the file for 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 for the txt file:
/home/Desktop/example/
bla bla bla
bla bla bla
As you understand, the problem is when I'm sending the path from main() function, list_dir() can't open the path and I get "Cannot open directory" as an error. Help?
As the commenters above said there is a newline at the end of dirPath and that's why you get Cannot open directory, add strtok(dirPath, "\n"); just before opendir to get rid of the trailing newline.
Also note that you are including some headers more than once and that main should return an int.
I tried to recursively get all files and folder list.But I can only get subdirectories of documents and inside of them.I can't get the other folders which in inside of subdirectory.
I don't know how to do it recursively.I hope you help me
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <windows.h>
#include <unistd.h>
#include <string.h>
void list(char *a);
void reader(char *path);
int
main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("C:\\Users\\pen\\Documents\\");
if (dp != NULL)
{
while (ep = readdir (dp)){
GetFileAttributes(ep->d_name);
if(FILE_ATTRIBUTE_DIRECTORY & GetFileAttributes(ep->d_name))
{
if (strcmp(".",ep->d_name)==0)
continue;
if (strcmp("..",ep->d_name)==0)
continue;
reader(ep->d_name);
}
}
closedir(dp);
}
else
perror ("Couldn't open the directory");
closedir(dp);
system("pause");
return 0;
}
void reader(char *path){
DIR *da;
struct dirent *ef;
da = opendir(path);
while (ef=readdir(da)){
printf ("%s\n",ef->d_name);
if(FILE_ATTRIBUTE_DIRECTORY & GetFileAttributes(ef->d_name))
{
if (strcmp(".",ef->d_name)==0)
continue;
if (strcmp("..",ef->d_name)==0)
continue;
reader(ef->d_name);
}
}
closedir(da);
}
1) In reader you need to call closedir(da); after the while loop.
2) every call to reader needs to have the absolute path you need to concatenate path
to ef->d_name and then call reader.
3) also to enable debugging you should call perror after a failed readdir call.
I'm trying to create a function in c which scans all my path C: \ temp (Windows) to search for a file that I pass (eg test.txt) and each time it finds one return the path to steps another function to write something in the bottom of this file.
I managed to do the function that writes to the file but can not figure out how to do that scans the folder and pass the address of the file found.
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
int main()
{
printf("Directory scan of /home:\n");
printdir("/home",0);
printf("done.\n");
exit(0);
}
Use FindFirstFile function. Here's a good example of this function using.
I have to create a listing of the files contained inside a specific directory, I have done the code below(part of a bigger programm), but I would like my programm to ignore any possible folders that could be included inside the directory.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main ()
{
DIR *dirptr;
struct dirent *entry;
dirptr = opendir ("synchedFolder");
if (dirptr != NULL)
{
while (entry = readdir (dirptr))
{
if(strcmp(entry->d_name,"..")!=0 && strcmp(entry->d_name,".")!=0)
puts (entry->d_name);
}
(void) closedir (dirptr);
}
else
perror ("ERROR opening directory");
}
If you want to list only files, but no directories, you have to add the following check:
entry->d_type == DT_REG
or
entry->d_type != DT_DIR
There's stat() and lstat() and the return value for stat. In the latter, look out for the S_ISDIR macro.
Short answer is the dirent structure includes the necessary information:
if ( entry->d_type == DT_REG)
Check stat (or lstat)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
/* int main (void){ */
int main (int argc, char **argv){
int i,result=0;
struct stat buf;
/* print_S_I_types(); */
for (i=1; i < argc; i++){
if (lstat(argv[i], &buf) < 0) {
fprintf(stderr, "something went wrong with %s, but will continue\n",
argv[i]);
continue;
} else {
if S_ISREG(buf.st_mode){
printf("argv[%d] is normal file\n",i);
}else {
printf("argv[%d] is not normal file\n",i);
}
}
}
return 0;
}
Working code for listing files (without directories):
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main()
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("/home/images")) != NULL)
{
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL)
{
if(ent->d_type!= DT_DIR)
{
printf ("%s\n", ent->d_name);
}
}
closedir (dir);
}
else
{
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
}
I try to write program where part of it is listing all directories (especially starting from /), but I have a problem with /proc/self which is infinitely recursive (I get /proc/self/task/4300/fd/3/proc/self/task/4300/fd/3/proc/self/task/4300/fd/3/proc/... and so on). What is nice way to deal with it?
EDIT: Program is written in C language and I use opendir(), readdir()
You can use the S_ISLNK macro to test the st_mode field returned by a call to lstat. If the file is a symbolic link, do not try to follow it.
[user#machine:~]:./list | grep link
/proc/mounts is a symbolic link
/proc/self is a symbolic link
Example code
#include <stdio.h> // For perror
#include <stdlib.h>
#include <sys/types.h> // For stat, opendir, readdir
#include <sys/stat.h> // For stat
#include <unistd.h> // For stat
#include <dirent.h> // For opendir, readdir
const char *prefix = "/proc";
int main(void)
{
DIR *dir;
struct dirent *entry;
int result;
struct stat status;
char path[PATH_MAX];
dir = opendir(prefix);
if (!dir)
{
perror("opendir");
exit(1);
}
entry = readdir(dir);
while (entry)
{
result = snprintf(path, sizeof(path), "%s", prefix);
snprintf(&path[result], sizeof(path) - result, "/%s", entry->d_name);
printf("%s", path);
result = lstat(path, &status);
if (-1 == result)
{
printf("\n");
perror("stat");
exit(2);
}
if (S_ISLNK(status.st_mode))
{
printf("%s", " is a symbolic link");
}
printf("\n");
entry = readdir(dir);
}
return(0);
}
From path_resolution(7):
Length limit
There is a maximum length for pathnames. If the pathname (or some intermediate pathname obtained while resolving symbolic links) is too long, an ENAMETOOLONG error
is returned ("File name too long").
I think you should employ similar behaviour: check for too long pathnames.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/param.h>
/* Short & sweet recursive directory scan, finds regular files only.
Good starting point, should work on Linux OS.
Pass the root path, and returns number of dirs and number of files
found.
*/
char *tree_scan( const char *path, int *ndirs, int *nfiles){
DIR *dir;
struct dirent *entry;
char spath[MAXPATHLEN] = "";
if( !(dir = opendir( path))){ perror("opendir"); exit(1);}
for( entry = readdir( dir); entry; entry = readdir( dir)){
sprintf( spath, "%s/%s", path, entry->d_name);
if( entry->d_type == DT_REG){ (*nfiles)++; printf( "%s\n", spath);}
if( entry->d_type == DT_DIR &&
(strcmp( ".", entry->d_name)) &&
(strcmp( "..", entry->d_name))){
(*ndirs)++; tree_scan( spath, ndirs, nfiles);
}
}
closedir( dir);
return(0);
}
/* Call it like so */
int i = 0, l = 0;
tree_scan( "/path", &i, &l);
printf("Scanned %d directories, %d files.\n", i, l);
I don't have a *nix terminal handy, but you could always take a look at the source for ls.c and see how it's done.
The source as part of the gnu core utils can be found here.
I created a ls clone a few years ago in school, and I think I got around it by watching the pathname size as ulidtko mentioned.