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

Ajith C Narayanan

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

ThiefMaster

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related