0

As the Title says, i am trying out this last year's problem that wants me to write a program that works the same as scanf(). Ubuntu:

Here is my code:

#include<unistd.h>
#include<stdio.h>
int main()
{
int fd=0;
char buf[20];
read(0,buf,20);
printf("%s",buf);
}

Now my program does not work exactly the same. How do i do that both the integer and character values can be stored since my given code just takes the character strings. Also how do i make my input to take in any number of data, (only 20 characters in this case).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
Kraken
  • 23,393
  • 37
  • 102
  • 162

1 Answers1

1

Doing this job thoroughly is a non-trivial exercise.

What you show does not emulate sscanf("%s", buffer); very well. There are at least two problems:

  1. You limit the input to 20 characters.
  2. You do not stop reading at the first white space character, leaving it and other characters behind to be read next time.

Note that the system calls cannot provide an 'unget' functionality; that has to be provided by the FILE * type. With file streams, you are guaranteed one character of pushback. I recently did some empirical research on the limits, finding values that the number of pushed back characters ranged from 1 (AIX, HP-UX) to 4 (Solaris) to 'big', meaning up to 4 KiB, possibly more, on Linux and MacOS X (BSD). Fortunately, scanf() only requires one character of pushback. (Well, that's the usual claim; I'm not sure whether that's feasible when distinguishing between "1.23e+f" and "1.23e+1"; the first needs three characters of lookahead, it seems to me, before it can tell that the e+f is not part of the number.)

If you are writing a plug-in replacement for scanf(), you are going to need to use the <stdarg.h> mechanism. Fortunately, all the arguments to scanf() after the format string are data pointers, and all data pointers are the same size. This simplifies some aspects of the code. However, you will be parsing the scan format string (a non-trivial exercise in its own right; see the recent discussion of print format string parsing) and then arranging to make the appropriate conversions and assignments.

Unless you have unusually stringent conditions imposed upon you, assume that you will use the character-level Standard I/O library functions such as getchar(), getc() and ungetc(). If you can't even use them, then write your own variants of them. Be aware that full integration with the rest of the I/O functions is tricky - things like fseek() complicate matters, and ensuring that pushed-back characters are properly consumed is also not entirely trivial.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278