Isharth Rastogi Isharth Rastogi - 25 days ago 9
Linux Question

Open() system call doesnt work in combination with DIR directory pointer

Open() system call doesn't work in this code. However, they work normally if not used with combination to directory pointer. here i have used file->d_name to access the string base address to open the file but it doesn't work and prints error.

#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<dirent.h>
#include<unistd.h>
#include<sys/dir.h>

int main()
{
DIR* d=opendir("DDD");
struct dirent* file;
int fd;
char WBUFFER[]="IO OS system calls\n";
char RBUFFER[100001];

while((file=readdir(d))!=NULL)
if(strlen(file->d_name)>=10)
{
if((fd=open(file->d_name,O_RDWR,0))==-1)
printf("error\n");
read(fd,RBUFFER,101);
printf("%s",RBUFFER);
close(fd);
}
else if(strlen(file->d_name)>=3)
{
if((fd=open(file->d_name,O_RDWR,0))==-1)
printf("error2\n");
write(fd,WBUFFER,50);
close(fd);
}

}

Answer

file->d_name contains just the file name, not the relative or absolute path which open(2) requires. That's why open() fails (unless you happen to have files with the same name in your current directory as the directory DDD has).

You need to prepend the directory name to file->d_name using snprintf(), like:

char buf[PATH_MAX];
snprintf(buf, sizeof buf, "DDD/%s", file->d_name);

and use buf in your open() calls.