Unix Programming - Strange read problem

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > February 2007 > Strange read problem





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Strange read problem
Jack

2007-02-12, 7:20 am

Hi,

Below is a simple code:

#include <errno.h>
#include <fcntl.h>
#include <iostream.h>
using namespace std;
int main()
{
int handle;
char *BUF = "HELLO, HELLO[20]";
char b[10];
handle = creat("t/a", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);//
O_RDWR );
int ret = write(handle, BUF,
strlen(BUF)); //
LINE1
cout << "ret:" << ret << endl;
cout << "BUF:" << BUF << endl;
int err;
int r = read(handle,b,
10); //
LINE2
if ( r != 10 )
{
cout<<"r:"<<r<<" Errno:" <<errno<<" b:"<<b<<endl;
}
return 0;
}

The output of the code is:
> ./test

ret:16
BUF:HELLO, HELLO[20]
r:-1 Errno:9 b:T-??T-??T-??T-??T-??T-??T-??T-??

Why the read( ) at LINE2 failed, but the write( ) at LINE1 succeeded.
The errno 9 is:
#define EBADF 9 /* Bad file descriptor */

The file handle works for write( ), but does not work for read( ).
Why?
The system is IBM AIX. The compiler is xlC.

Thanks.

Jack

Stephane CHAZELAS

2007-02-12, 7:20 am

2007-02-12, 00:15(-08), Jack:
[...]
> handle = creat("t/a", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);//
> O_RDWR );

[...]
> Why the read( ) at LINE2 failed, but the write( ) at LINE1 succeeded.
> The errno 9 is:
> #define EBADF 9 /* Bad file descriptor */
>
> The file handle works for write( ), but does not work for read( ).
> Why?

[...]

creat() is to open a file in write-only mode. It's equivalent to
open(file, O_CREAT|O_WRONLY|O_TRUNC, mode). So you can't read
from a file open that way.

Use open(2) if you want to open a file in read-write mode. And
beware that when you do so, there's only one /cursor/ position
within the file. You can't read what you just wrote unless you
rewind within the file.

--
Stéphane
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com