Search code examples
cfilepermissionsfile-descriptor

why do O_RDWR doesn't give me write and read permission in this code?


I'm starting to be interested in file descriptors in C, i wrote the following code :

int main (void) 
{ 
    int fd1, fd2, sz;
    char *buf = "hello world !!!";
    char *buf2 = malloc(strlen(buf));

    fd1 = open ("test.txt", (O_RDWR | O_CREAT));
    printf("file fd1 created\n");
    write(fd1, buf, strlen(buf));
    printf("write %s, in filedescpror %d\n", buf, fd1);
    sz = read(fd1, buf2, strlen(buf)); 
    printf("read %s, with %d bytes from file descriptor %d\n", buf2, sz, fd1); 
    close(fd1);
    fd2 = open ("testcpy.txt", (O_RDWR | O_CREAT));
    write(fd2, buf2, strlen(buf));
    close(fd2);
    return 0; 
}

Normally:

  • two files with read and write permissions are provided,
  • buf is pasted into fd1
  • fd1 is read and the data is stored in bf2
  • bf2 is parsed into fd2

The first problem is that the permission that i get in the result aren't correct, what's happening is that something outside buf2 is parsed into fd2.

Can anyone tell me what's happening, is my code wrong, or is what's happening is the expected behavior.


Solution

  • You need to rewind the buff after the write(), and also add permissions (3rd arg of open()), this is a basic example:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <fcntl.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int main (void)
    {
        int fd1, fd2, sz;
        char *buf = "hello world !!!";
        char *buf2 = malloc(strlen(buf) + 1); // space for '\0'
    
        fd1 = open ("test.txt", (O_RDWR | O_CREAT), 777); // 3rd arg is the permissions
        printf("file fd1 created\n");
        write(fd1, buf, strlen(buf));
        lseek(fd1, 0, SEEK_SET);            // reposition the file pointer
        printf("write %s, in filedescpror %d\n", buf, fd1);
        sz = read(fd1, buf2, strlen(buf));
        buf[sz] = '\0';
        printf("read %s, with %d bytes from file descriptor %d\n", buf2, sz, fd1);
        close(fd1);
        fd2 = open ("testcpy.txt", (O_RDWR | O_CREAT));
        write(fd2, buf2, strlen(buf));
        close(fd2);
        return 0;
    }