Skip to content
Advertisement

When I program in Linux using C, I use the open or creat functions and end up behaving differently

//error handle
void my_err(const char* errno_string,int line){
    fprintf(stderr,"line:%d ",line);
    perror(errno_string);
    exit(1);
}

//self-definded read data function

int my_read(int fd){
    int len;
    int ret;
    int i;
    char read_buf[64];

    //get length of file and keep point of file at the srart
    if(lseek(fd,0,SEEK_END) == -1){
        my_err("lseek",__LINE__);
    }

    if((len = lseek(fd,0,SEEK_CUR)) == -1){
        my_err("lseek",__LINE__);
    }

    if(lseek(fd,0,SEEK_SET) == -1){
        my_err("lseek",__LINE__);
    }

    printf("len:%dn",len);

    //read data
    if((ret = read(fd,read_buf,len)) < 0){
        my_err("read",__LINE__);
    }

    //print data
    for(i = 0;i<len;i++){
        printf("%c",read_buf[i]);
    }

    printf("n");
    return ret;
}

int main()
{
    int fd;
    char write_buf[32] = "hello boy!";

    //create example2 in current directory
    if((fd = creat("example2.c",S_IRWXU)) == -1){
    // if((fd = open("example2.c",O_RDWR|O_CREAT|O_TRUNC,S_IRWXU)) == -1){
        my_err("open",__LINE__);
    }else{
        printf("craete file successn");
    }

    //write data
    if(write(fd,write_buf,strlen(write_buf)) != strlen(write_buf)){
        my_err("write",__LINE__);
    }
    my_read(fd);

    //Spacing of presentation files
    printf("/*------------*/n");
    if(lseek(fd,10,SEEK_END) == -1){
        my_err("lseek",__LINE__);
    }
    if(write(fd,write_buf,strlen(write_buf)) != strlen(write_buf)){
        my_err("write",__LINE__);
    }
    my_read(fd);
    close(fd);
    return 0;
}

Line 43 is this part of main

    //create example2 in current directory
    if((fd = creat("example2.c",S_IRWXU)) == -1){
        my_err("open",__LINE__);
    }else{
        printf("craete file successn");
    }

When I use creat, I get an error line:43 read: Bad file descriptor, but I get the correct result with open. Shouldn’t both functions return file descriptors? Why should creat return the wrong file descriptor

When I use creat, I get an error line:43 read: Bad file descriptor, but I get the correct result with open. Shouldn’t both functions return file descriptors? Why should creat return the wrong file descriptor enter image description here

Advertisement

Answer

Shouldn’t both functions return file descriptors?

They should and they do.

Why should creat return the wrong file descriptor

It shouldn’t and it doesn’t. read fails with Bad file descriptor error, not creat.

creat opens file write-only, so you can’t read from it. It’s a bad file descriptor if you want to read from it.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement