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.