Thread: Problem with read().(from K&R)

  1. #1
    Registered User
    Join Date
    May 2008
    Location
    India
    Posts
    30

    Problem with read().(from K&R)

    I am in the learning phase of c. I am reading K & R and trying to execute one of the program "listing directories".
    Code:
    #include "cDirent.h"
    #include<sys/stat.h>
    #include<string.h>
    #include<sys/types.h>
    #include "syscall.h"
    #include<fcntl.h>
    #include<sys/dir.h>
    #include<stdlib.h>
    #ifndef DIRSIZ
    #define DIRSIZ 14
    #endif
    
    Dir *copendir(char *dirname){
      int fd;
      struct stat stbuf;
      Dir *dp;
      if((fd=open(dirname,O_RDONLY,0)) == -1 || fstat(fd,&stbuf) == -1 || (stbuf.st_mode & S_IFMT) != S_IFDIR || (dp = (Dir *) malloc (sizeof(Dir))) == NULL)
        return NULL;
      dp->fd=fd;
      return dp;
    }
    
    void cclosedir(Dir *d){
      if(d){
        close(d->fd);
        free(d);
      }
    }
    
    Dirent *creaddir(Dir *dp){
      struct direct dirbuf;
      static Dirent d;
      int c;
      while((c=read(dp->fd,(char *) &dirbuf,sizeof(dirbuf))) == sizeof(dirbuf)){
        if(dirbuf.d_ino == 0)
          continue;
        d.inod = dirbuf.d_ino;
        strncpy(d.name,dirbuf.d_name,DIRSIZ);
        d.name[DIRSIZ]='\0';
        return &d;
      }
      return NULL;
    }
    .
    I am calling these function from other program. First I opened the directory and it went fine. But when i use the creaddir function,its giving me NULL, because the system call read is giving -1. I have debugged the program using gdb, and found that fd passed is 6, which i got from the copendir function.
    Can someone please help regarding this?
    Thank you.

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    When a system call returns error, you should check errno; in this case I suspect that read() is setting errno to EISDIR. That is, your read() probably refuses to read from a directory. POSIX provides opendir() and readdir() for reading directories. I suppose that using those functions to implement your own versions would be rather, boring, though!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  2. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  3. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  4. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  5. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM