1

I have to sum two number while first number is not equal to -1, and the numbers have just one digit. I have to use read() and write().

#include <unistd.h>
#include <errno.h>

int main()
{   int Somma;
    int One;
    int Two;

    do
    {   write(1, "\nFirst Number: ", 15);
        if(read(0, &One, sizeof(int)) == -1)
            perror("Error First Read");

        if(One != -1)
        {   write(1, "Second Number: ", 15);
            if(read(0, &Two, sizeof(int)) == -1)
                perror("Error Second Read");

            Somma = One + Two;
            Somma -= 48;

            write(1, "Sum: ", 5);
            if(write(1, &Somma, sizeof(int)) == -1)
                perror("Error Write");
        }

    }while(One != -1);

    return 0;
}

Now, I have some problems. First of all, when One is equal to -1, the program continues into if statement... The second one is that the last write(), print the number and a strange characters (a square with 0014 code into...). What's wrong?

Thank you in advance

Federico Cuozzo
  • 363
  • 1
  • 7
  • 20
  • Is there any reason you're not using glibc functions like printf(3) and scanf(3)? You're using `read(2)` wrong, reading 4 bytes, which is equal to 4 characters. `read(2)` reads binary data, not actual characters. – holgac Apr 03 '15 at 15:33
  • The professor says that we have to use read() and write() in unistd.h library... – Federico Cuozzo Apr 03 '15 at 15:35
  • 2
    Oh ok. Besides from the answer below, I'd like to say that since you're working on linux, try a little not to capitalize the first letter in your variable names. Another thing is, use `STDIN_FILENO` instead of 0 and `STDOUT_FILENO` instead of 1 in `read(2)` and `write(2)` calls. It'll be easier to read. – holgac Apr 03 '15 at 15:37
  • Are you supposed to read the numbers via stdin? – teppic Apr 03 '15 at 15:45
  • In this exercize, I have to read via stdin...in the next one I will have to read from an input file... – Federico Cuozzo Apr 03 '15 at 16:03

1 Answers1

0

I guess you are on Linux or some POSIX system.

The read(2) & write(2) syscalls are reading bytes. On modern Linux systems the terminal is usually using UTF-8 encoded strings (which you might process using libunistring if you have to). For efficiency reasons, you should (manually) buffer the I/O, i.e. try to read or write in blocks of several kilobytes (typically 16Kbytes).

You should obviously handle the byte count (returned by these syscalls). Don't forget to handle error conditions (e.g. by displaying them with perror(3) then exit(EXIT_FAILURE);)

Your code is wrong, because sizeof(int) is often 4, and your call to read might read only 1,2, or 3 bytes (but very often, it would read 4 bytes). You have to handle buffering, and that is part of the exercise.

You could use sscanf(3) and snprintf(3) to make the string to int conversions and backwards. Don't forget the error cases.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547