/*****************************************************\
* Filename: io.c
* Author: Sue Bogar
* Date written: 11/28/97
* Date modified: 7/26/2000
* Section: 101
* EMail: bogar@cs.umbc.edu
*
* Description: This is code shows the practical
* differences between fgetc, fgets and
* fscanf when getting a string from
* a file.
\*****************************************************/
#include
#include
int main ( )
{
FILE *ifp;
char string[100], filename[20];
int ch;
/* Get filename from user */
printf ("Enter the name of the text file to be examined: ");
scanf ("%s", filename);
printf ("\n");
/* Open the file */
ifp = fopen(filename, "r");
if (ifp == NULL)
{
fprintf (stderr, "Couldn't open '%s' ... Exiting program\n",
filename);
exit (-1);
}
/* Read one character into the string */
string[0] = fgetc(ifp);
/* Put the null terminator at the end */
string[1] = '\0';
printf("This is the string fgetc got :\n\n");
printf("%s\n\n", string);
rewind (ifp);
/* Now look at fscanf */
fscanf(ifp, "%s", string);
printf("This is the string fscanf got :\n\n");
printf("%s\n\n", string);
rewind (ifp);
/* Now look at fgets */
fgets(string, 100, ifp);
printf("This is the string fgets got :\n\n");
printf("%s\n", string);
/* close the file */
fclose (ifp);
return 0;
}
The Example File
This is an example text file. It is used with the
lecture about I/O. Most of the time sentences
continue across several lines. Newlines can occur
anywhere within a sentence. The file may also
contain numbers, as in the students in Sue's
CMSC 201 class will get to see this example.
The Sample Run
Enter the name of the text file to be examined: example.txt
This is the string fgetc got :
T
This is the string fscanf got :
This
This is the string fgets got :
This is an example text file. It is used with the