home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.unix.programmer
- Path: sparky!uunet!caen!batcomputer!snake.tc.cornell.edu!reed
- From: reed@snake.tc.cornell.edu (Michael G. Reed)
- Subject: Re: Trying to write my own ls
- Message-ID: <1992Sep9.170531.27422@tc.cornell.edu>
- Keywords: inodes
- Sender: news@tc.cornell.edu
- Nntp-Posting-Host: snake.tc.cornell.edu
- Reply-To: reed@TC.Cornell.EDU
- Organization: Cornell National Supercomputing Facility
- References: <1992Sep9.125031.17878@monu6.cc.monash.edu.au>
- Date: Wed, 9 Sep 1992 17:05:31 GMT
- Lines: 49
-
- In article <1992Sep9.125031.17878@monu6.cc.monash.edu.au>, int233p@mdw033.cc.monash.edu.au (Mr A.J. Bucknell) writes:
- |> I am trying to write a small program that lists the files and subdirectories
- |> of a specified directory. I have got the following program running, and it
- |> works fine when I run it on the home directory, but when I run it on any other
- |> directory, it gives incorrect file sizes. Can anyone point my error ? The
- |> code is :
- |>
- |>
- |> #include <stdio.h>
- |> #include <sys/types.h>
- |> #include <sys/dir.h>
- |> #include <sys/stat.h>
- |>
- |> void main(int argc, char *argv[])
- |> {
- |> struct stat buf;
- |> DIR *dirp;
- |> struct direct *dp;
- |>
- |> dirp = opendir(argv[1]);
- |> for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp))
- |> {
- |> stat(dp->d_name, &buf);
-
- BINGO! Here's your problem. The string pointed to by dp->d_name is local to
- the directory, not global to the filesystem. Therefore, when you the stat on the
- files, it is checking your CURRENT directory (not the directory you want it to
- check) for the file information. You could get around this by prepending argv[1]
- to dp->d_name in temporary memory before doing the stat, or by issuing a
- chdir(argv[1]) at the beginning of your code. Does anyone know if fchdir(dirp)
- might work (I didn't take a look at the structure definitions for FILE and DIR)?
-
- |> printf("%-15s%8d\n", dp->d_name, buf.st_size);
- |> }
- |> closedir(dirp);
- |> }
- |>
- |> Thanks in advance for any help. Replies via email, or to here if you think its
- |> of interest to others.
-
- -Michael
-
- -----------------------------------------------------------------------------
- Michael G. Reed (reed@TC.Cornell.EDU)
- Cornell National Supercomputing Facility (607)/254-8806
- -----------------------------------------------------------------------------
- Why be normal, it's boring; and boring people should be shot.
-
- Note: These are not the views of my employer (and probably not mine either).
-