Re: Beginner with read() and write(), have a couple of questions



On Mar 3, 10:33 pm, Paul Pluzhnikov <ppluzhnikov-...@xxxxxxxxxxx>
wrote:
"dtscho...@xxxxxxxxx" <dtscho...@xxxxxxxxx> writes:
int x, counter, in, bytesR;
char buf[1024];
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /* 0666*/

Mode is ignored, unless you do O_CREAT (which you don't and
shouldn't). You could just as well use 0 for mode.

double y;
in = open("numbers", O_RDONLY, mode);
printf("fd: %i\n", in);

bytesR = read(in, buf, sizeof(x));
printf("bytes read: %i\n", bytesR);

Presumably this prints "bytes read: 4"

printf("%x\n", x);

Here you are printing value of 'x', but you never initialized it.
Instead you read the value into 'buf'. Perhaps you want to do
this instead:

bytesR = read(in, &x, sizeof(x));


Not sure how I overlooked that one. I modified my code and it now
displays the '5' correctly when running the program. The next problem
is that the doubles are not being printed. I have modified my code
again and it shows it is reading in 8 bytes for the doubles but they
all print as 0 (zero). Here's the code and my output...

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
int x, counter, in, bytesR;
double y;
in = open("numbers", O_RDONLY);

bytesR = read(in, &x, sizeof(x));
printf("%x\n", x);

for(counter = 0; counter < x; counter++)
{
bytesR = read(in, &y, sizeof(y));
printf("bytes read: %i\n", bytesR);
printf("%d\n", y);
}

return 0;
}

**************************************

5
bytes read: 8
0
bytes read: 8
0
bytes read: 8
0
bytes read: 8
0
bytes read: 8
0

David


.



Relevant Pages


Loading