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

Think About What You're Getting

Different input functions are better suited to handling different kinds of input, which is why more than one of them exists in the first place. Think about what you are reading in and why before you decide which function to use.

For example, suppose you are finding the areas of a bunch of rectangles. The data to be read in could logically be a file with two ints on a line. Reading in two ints at a time with fscanf() makes a lot more sense than using fgets() and writing complicated code to split up the string and then change each part into integers

Example Code

Using fscanf (good)

while (fscanf(ifp, "%d %d", &height, &width) != EOF ) { printf("The area of a rectangle with height %d", height); printf(" and width %d is %d.\n", width, height*width); }

Using fgets (bad)

while (fgets(string, 100, ifp) != NULL ) { tokenPtr = strtok(string, " "); height = atoi(tokenPtr); tokenPtr = strtok(NULL, " "); width = atoi(tokenPtr); printf("The area of a rectangle with height %d", height); printf(" and width %d is %d.\n", width, height*width); } Besides being longer and ugly, this code also requires the use of an extra variable and an extra string and including an extra .h file. Writing the code itself is also much more complicated.

Sometimes it isn't a matter of a bad choice meaning more complicated code. Sometimes things that you think would work just won't. For example, if you want to copy a file full of text, using fscanf() with %s to read in the file one word at a time will not be able to recreate the file. Since fscanf() will break at any whitespace, including tabs and newlines, recreating the file by spitting out the strings with spaces in between them will make one long line of text that wraps off the screen.

However, fgets only stops at a newline character, so reading in strings using fgets() and putting newlines between each string when recreating the file is guaranteed to be the same as the original.


CSEE | 201 | 201 S'02 | lectures | news | help

Last Modified - Wednesday, 10-Apr-2002 18:56:12 EDT