UMBC CS 201, Fall 06
UMBC CMSC 201
Fall '06

CSEE | 201 | 201 F'06 | 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 exist 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 an integer.

Example Code

Using fscanf (good choice for this data file)

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 choice for this data file)

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 and includes the newline character in the string. So reading in strings using fgets() will let you recreate the file and it will be the same as the original.


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

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