Mitchapp Mitchapp - 3 months ago 13
C Question

C: Reading double from stdin using read system call

I am asking how can to read a double, int or any other types from stdin using the read system call.
What I've done so far:

long val ;
ssize_t r;
r = read(STDIN_FILENO,&val,sizeof(long));
printf("%ld\n",val);


That doen't give me what I want.

Answer

You are not being clear whether you want to read (a) the ASCII representation of a long, double, int or whatever (i.e. the string "0.12345", or (b) the binary representation of that value.

If you want to do (a), you need to use fscanf. See the above answer.

If you want to do (b), your code looks right to me. What is the 'bad result' you are having? Did you check for r<0, then look at errno or use perror().

I suspect the problem is you wanted to do (a), but have coded for (b).

Comments