简体   繁体   中英

read() returns Bad file descriptor on a valid file descriptor

In the following program,

int main()
{
    int fd;
    char buf[8]={};

    remove("file.txt");
    fd = creat("file.txt",0666);
    write(fd,"asdf",5);
    perror("write");
    lseek(fd,0,SEEK_SET);
    perror("lseek");
    read(fd,buf,5);
    perror("read");
    printf("%s\n",buf);
    return 0;
}

My expected output is

write : Success
lseek : Success
Read : Success
asdf

But it shows

wriet : Success
lseek : Success
Read : Bad file descriptor

Can anybody tell me the reason? I can see that the string "asdf" if successfully written to file.txt

From the manpage:

The creat() function shall behave as if it is implemented as follows:

 int creat(const char *path, mode_t mode) { return open(path, O_WRONLY|O_CREAT|O_TRUNC, mode); } 

So, the file is opened in write-only mode and thus you cannot read.

If you need to read and write, use open(...) directly with O_RDWR instead of O_WRONLY .

The 0666 you specified just indicates the permissions in the file system the file gets created with.

If you just want to do normal file I/O you could also use the high-level APIs such as fopen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM