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 ...
- 06-24-2010 #1Just 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);
- 06-24-2010 #2Just 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.


Reply With Quote