473,770 Members | 5,136 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

readdir not reading subdirectories properly

849 Recognized Expert Contributor
My Operating Systems professor has assigned homework that basically boils down to implementing ls -lra, but with a different output format. In other words, list the files and subdirectories (and a bit of data about them, for the files) in the current directory and its subdirectories using system calls. Unfortunately, it isn't working quite right. It works fine in the current directory, but when it goes into subdirectories, the stat() function always returns -1 (failure, error message is No such file or directory), yet when I print out the path and cd to the directory, the file is there. This is all occurring on FreeBSD 6.3 with gcc 3.4.6.

Expand|Select|Wrap|Line Numbers
  1. /* <name and email removed to protect the (sort of) innocent>
  2.  * This program lists all files and directories contained within the present working directory and its subdirectories.
  3.  * The following information is printed about each file: <filename> <size in bytes> <date and time last modified>
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <dirent.h>
  10. #include <errno.h>
  11. #include <string.h>
  12. #include <time.h>
  13. #include <stdlib.h>
  14. #include <unistd.h>
  15. #include <sys/param.h>
  16.  
  17. extern int errno;
  18.  
  19. void read_directory(const char* dirpath, int numspaces);
  20. void print_file(struct dirent* file, struct stat* sb, int numspaces, char isdir);
  21.  
  22. int main(){
  23.     read_directory("./", 0);
  24.     return 0;
  25. }
  26.  
  27. void read_directory(const char* dirpath, int numspaces){
  28.     struct dirent* entry;
  29.     DIR* dir = opendir(dirpath);
  30.     if (dir == NULL){
  31.         perror("Error reading directory: ");
  32.         return;
  33.     }
  34.     while ((entry = readdir(dir))){ //keep reading as long as there's something to read
  35.         if (entry == NULL) //all done or an error
  36.             return;
  37.         else if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0)) //need to avoid infinite recursion!
  38.             continue;
  39.         struct stat* sb = (struct stat*) (malloc(sizeof(struct stat*)));
  40.         if (sb == NULL){
  41.             printf("Error allocating for stat pointer!\n");
  42.             return;
  43.         }
  44.         int i = stat(entry->d_name, sb); //This is the problematic call
  45.         if (i == -1){
  46.             printf("Attempting to read %s, but %s\n", entry->d_name, strerror(errno));
  47.             return;
  48.         }
  49.         else if (S_ISDIR(sb->st_mode)){
  50.             char* cwd = (char*)(malloc(MAXPATHLEN)); //gives 1023B
  51.             cwd = getcwd(cwd, MAXPATHLEN);
  52.             if (cwd == NULL){
  53.                 printf("Error allocating absolute pathname!\n");
  54.                 return;
  55.             }
  56.             sprintf(cwd, "%s/%s", cwd, entry->d_name);
  57.             print_file(entry, sb, numspaces, 1);
  58.             read_directory(cwd, numspaces+4);
  59.             free(cwd);
  60.         }
  61.         else if (S_ISREG(sb->st_mode)){
  62.             print_file(entry, sb, numspaces, 0);
  63.         }
  64.         free(sb);
  65.     }
  66. }
  67.  
  68. void print_file(struct dirent* file, struct stat* sb, int numspaces, char isdir){
  69.     int i; //gcc 3.4 doesn't support bools as a builtin, seemingly
  70.     char spaces[numspaces+1];
  71.     spaces[numspaces] = '\0';
  72.     for (i = 0; i < numspaces * sizeof(char); i++)
  73.         spaces[i] = ' ';
  74.     if (!isdir){
  75.         char* clock = (char*)(malloc(27));
  76.         if (clock == NULL){
  77.             printf("Error allocating for clock characters!\n");
  78.             return;
  79.         }
  80.         ctime_r(&(sb->st_mtime), clock);
  81.         printf("%s%s %d %s", spaces, file->d_name, (unsigned int)(sb->st_size), clock);
  82.         free(clock);
  83.     }
  84.     else
  85.         printf("%s%s\n", spaces, file->d_name);
  86. }
I have no idea what causes this, also when it goes into the subdirectories, it only looks at the first file if there's multiple. My only guess is that it might be an issue with how I obtain the absolute path...
Aug 30 '08 #1
4 7268
JosAH
11,448 Recognized Expert MVP
Expand|Select|Wrap|Line Numbers
  1. struct stat* sb = (struct stat*) (malloc(sizeof(struct stat*)));
  2.  
The line above is line #39 in your program; you should allocate enough room for
an entire struct stat, not just enough room for a struct stat pointer.

kind regards,

Jos
Aug 30 '08 #2
Laharl
849 Recognized Expert Contributor
Whoops! Good catch on that one. Unfortunately, that doesn't fix the main problem.
Aug 30 '08 #3
JosAH
11,448 Recognized Expert MVP
Then print out that dirpath parameter when you (recursively) enter that function
and see the constructed path names ...

kind regards,

Jos

edit: also the stat() function needs an absolute path name, not a relative one.
Aug 30 '08 #4
Laharl
849 Recognized Expert Contributor
Thanks a ton, Jos! It turned out to be a pathname issue to stat() after all.
Aug 30 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

8
4623
by: Oliver | last post by:
Hi, I wrote earlier this day about this problem but thought it had something to do with images. However, I found out that for some reason the readdir function is not working properly on my Suse 9.1 server. I can only read a random number of files and directories per folder. When I repeat the command for the same folder I get the same output. If I use the readdir test script on an older machine everything works fine.
7
13868
by: Ask Josephsen | last post by:
Hi NG In wich order does "readdir()" read files from the disc? I've got an image folder with images in the format "00001.jpg", "00002.jpg" etc. It seems "readdir()" read the lowest first, but is it certain? An alternative is to read the files into an array and sort them, does anyone have any experience with this? Should I use the "SORT_REGULAR", "SORT_NUMERIC" or "SORT_STRING"?
2
8930
by: Matt | last post by:
Hello, I am writing a script that opens needs to get a listing of files in a directory, print that listing to a file and use that file as a quasi ftp control file. My problem is that when I print the filenames found via the readdir I also get the . and .. (current directory and parent directory) written in the ftp control file which causes my script to stop since you can't ftp . nor .. Here's my logic ....
21
2947
by: AES/newspost | last post by:
My understanding -- I'm not an expert -- is that on (some? many? all?) standard Internet servers a URL can point to a subdirectory name followed by a backslash, and that links to this URL will automatically go to an "index.html" file located in that subdirectory, if there is one. Q1: Is this more or less correct? At least some HTML texts also recommend using this as the basis for organizing a web site: Put the web pages associated...
1
2398
by: Benton | last post by:
Hi there, I want to have an unrestricted root directory and some protected subdirectories on my ASP.NET 2.0 application. I want each subdirectory to have its own Login.aspx page. The following article is a good start, but it uses a single Login.aspx located in the root directory to protect a subdirectory: http://www.theserverside.net/tt/articles/showarticle.tss?id=FormAuthentication
2
2511
by: kamalak | last post by:
hi, can someone help me in writing code in C# for getting the no of files in a directory and all its subdirectories and their subdirectories where the no of subdirectories and their subdirectories are not known. for example, to get the total no of files in C: or E: or so. thanks, kamala
9
3536
by: Confused but working on it | last post by:
Just wanted to say thanks for the posts helping me make ths work. Added a few comments and after the readdir used a pattern match to test for ..jpg, and seems to work fine on my test setup. Maybe I should test for gif, tiff, and png... Anyway, here's the code: <?php //Open images directory $dir = opendir("images"); //read files in the dir while (($file = readdir($dir)) !== false) //test to make sure jpg
1
1384
by: mukeshrasm | last post by:
Hi, When I used readdir() function and echo the file name it prints . and .. as well.Whereas there is no such file with name . or.. , so why it is printing it. What does it mean? And one more thing why we should loop over directory like while(false!==($file=readdir($direname))) why not like this while($filename=readdir($dirname))
2
3800
by: dj | last post by:
Hello All, I am attempting to us os.walk to populate two lists with values from a directory. The first list contains all the files in the directory and subdirectories. The second list contains only the files in the subdirectories. Here is the code: import os
0
9592
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10230
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9870
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8886
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7416
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6678
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3972
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2817
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.