confused with read() [Archive] - C Board

PDA

View Full Version : confused with read()


_EAX
03-15-2008, 03:27 PM
i m reading the book "linux system programming" and i get a little confused with read function.

here is the code from the book.


unsigned long word;
ssize_t nr;
/* read a couple bytes into 'word' from 'fd' */
nr = read (fd, &word, sizeof (unsigned long));
if (nr == -1)
/* error */


so why to read 4 bytes (unsigned long) when char is 1 byte? because if we read a file, everything in it will be character.

another example from the book...

assuming that len again is unsigned long ...



while (len != 0 && (ret = read (fd, buf, len)) != 0) {
if (ret == -1) {
if (errno == EINTR)
continue;
perror ("read");
break;
}

printf("%c", buf);

len -= ret;
buf += ret;


}


i tried that but it's not working properly, so i needed to modify in my way



int len = sizeof(char);
int broj=0;

while((ret = read(fd, &buf, len )) != 0 ){ // read 1 byte (char) and store it in buf

if(ret == -1){
if(errno == EINTR)
continue;
perror("read");
break;
}
printf("%c", buf);
}


tnx

Mortissus
03-17-2008, 08:19 AM
so why to read 4 bytes (unsigned long) when char is 1 byte? because if we read a file, everything in it will be character.


You must see a file as a storage of bytes. You can read and write anything from/into it. You could write an integer, for example, in this case, the file is binary.

It was a short answer, because the subject itself is very simple. You must understand the concept first. Ask yourself: how an application that display images would load a file? Is an image file a text? etc...

Hope that helps.

_EAX
03-17-2008, 04:14 PM
you are right, i totally forgot about binary files :) . tnx for the help.