UMBC CMSC 201 Spring '02 CSEE | 201 | 201 S'02 | lectures | news | help

scanf vs fscanf
printf vs fprintf

  • From the man page for scanf and friends, we notice that scanf knows to read 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"); } It would be better to use : array = (int *)malloc(size * sizeof(int)); if (array == NULL) { fprintf (stderr, "Out of memory - allocating array\n"); } 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 S'02 | lectures | news | help