Find the answer to your Linux question:
Results 1 to 2 of 2
I just started messing around in Linux programming, and I wanted to create a simple test program to open a file, read to it, and write to it. I can ...
  1. #1
    Just Joined!
    Join Date
    Jun 2010
    Posts
    2

    EBADF using write() in C

    I just started messing around in Linux programming, and I wanted to create a simple test program to open a file, read to it, and write to it. I can open and read it, but write always gives errno = EBADF. I've messed with file creation permissions and I can figure out why write() thinks it's a bad file descriptor but not read(). Any help would be appreciated.

    Here is my code:


    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>

    #include <unistd.h>

    #include <iostream>

    #include <string.h>

    #include <stdio.h>

    using namespace std;

    int main()
    {
    cout << "Hello World!\n";

    int fd;
    fd = open("/home/mike/OPEN.txt",O_APPEND | O_CREAT | O_NONBLOCK, (mode_t)0x666);

    cout << fd << endl;

    char *buf;
    ssize_t readret;
    readret = read(fd, buf, (size_t)10);

    cout << buf[0];
    perror("read");

    ssize_t ret;
    char *words = "What up";
    ret = write(fd, words, (size_t)strlen(words));

    cout << ret;
    perror("write");

    close(fd);

  2. #2
    Just Joined!
    Join Date
    Jun 2010
    Posts
    2
    Haha I found it!

    open() must use one of these flags among others:

    O_RDONLY, O_WRONLY, O_RDWR

    using O_RDWR makes it work.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...