/****************************************************************************\
* Filename: io.c *
* Author: Sue Bogar *
* Date written: 11/28/97 *
* Description: This is code shows the practical differences between fgetc *
* fgets and fscanf to get a string from a file. *
\****************************************************************************/
#include
#include
main ( )
{
FILE *ifp;
char *string, filename[20];
int ch, i, length = 0;
/* 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);
}
/* Find the number of characters in the file by
traversing and counting as we go, stopping when
fgetc returns end-of-file, EOF NOTE: ch has to
be declared as an int for this to work */
while ((ch = fgetc(ifp)) != EOF)
{
length++;
}
/* Rewind the file so we're back at the beginning */
rewind(ifp);
/* malloc enough space to hold the entire contents
of the file in a single string */
string = (char *)malloc((length + 1) * sizeof(char));
if (string == NULL)
{
fprintf(stderr, "Memory allocation failed for string\n");
exit (-1);
}
/* Read one character at a time into the string */
for (i = 0; i < length; i++)
{
string[i] = fgetc(ifp);
}
/* Put the null terminator at the end */
string[i] = '\0';
printf("This is the string fgetc got :\n\n");
printf("%s\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, length + 1, ifp);
printf("This is the string fgets got :\n\n");
printf("%s\n", string);
/* close the file */
fclose (ifp);
}
The Sample Run
retriever[102] cc io.c
retriever[103] a.out
Enter the name of the text file to be examined: example.txt
This is the string fgetc got :
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 367 students
in Sue's CMSC201 class will get to see this example.
This is the string fscanf got :
This
This is the string fgets got :
This is an example text file. It is used with the lecture about I/O. Most of
retriever[104]