UMBC CMSC 201
Fall '06

CSEE | 201 | 201 F'06 | lectures | news | help

scanf vs fscanf
printf vs fprintf

From the man page for scanf( ), we notice that scanf reads from the standard input stream, whereas fscanf( ) takes the stream from which to read as its first argument, in the form of a FILE pointer.

  int scanf(const char *format, ...);
  int fscanf(FILE *strm, const char *format,...);

  scanf reads from the standard input stream, stdin.

  fscanf reads from the stream strm.

So the following statements are equivalent :

scanf ("%d", &num); fscanf(stdin, "%d", &num);

Similarities also exist with the printf and fprintf functions. So the following statements are equivalent :

printf ("num = %d\n", num); fprintf (stdout, "num = %d\n", num);

Now that you know about, stderr, it is good programming practice to print error messages to stderr, rather than to stdout.
So rather than using the following :

array = (int *)malloc(size * sizeof(int)); if (array == NULL) { printf ("Out of memory - allocating array\n"); exit (-1); } It would be better to use : array = (int *)malloc(size * sizeof(int)); if (array == NULL) { fprintf (stderr, "Out of memory - allocating array\n"); exit (-1); } Why ?
If the user has chosen to redirect the output of his program into a file, the error message will still appear on the screen.


CSEE | 201 | 201 F'06 | lectures | news | help

Last Modified - Tuesday, 22-Aug-2006 07:14:07 EDT