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


open() system call doesn't work in code. however, work if not used combination directory pointer. here have used file->d_name access string base address open file doesn't work , 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);     }  } 

file->d_name contains file name, not relative or absolute path open(2) requires. that's why open() fails (unless happen have files same name in current directory directory ddd has).

you need prepend directory name file->d_name using snprintf(), like:

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

and use buf in open() calls.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -