Thread: confused with read()

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    2

    confused with read()

    i m reading the book "linux system programming" and i get a little confused with read function.

    here is the code from the book.

    Code:
    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 ...

    Code:
    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

    Code:
    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

  2. #2
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    Quote Originally Posted by _EAX View Post
    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.

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    2
    you are right, i totally forgot about binary files . tnx for the help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 06-17-2008, 11:38 AM
  2. Weird read input or bad printf output?
    By ChaoticMachiner in forum C Programming
    Replies: 3
    Last Post: 05-04-2008, 03:40 PM
  3. I am lost on how to read from file and output to file?
    By vicvic2477 in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2005, 11:52 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Getting size read with ifstream and read()
    By nickname_changed in forum C++ Programming
    Replies: 13
    Last Post: 08-03-2003, 06:05 AM