Important Notice
The pages on this site contain documentation for very old MS-DOS software,
purely for historical purposes.
If you're looking for up-to-date documentation, particularly for programming,
you should not rely on the information found here, as it will be woefully
out of date.
FUNGET.C
◄Up► ◄Contents► ◄Index► ◄Back►
────────────────────────────────────────────────────────────────────────────
/* FUNGET.C illustrates getting and ungetting characters from a file.
* Functions illustrated include:
* getc getchar ungetc
* fgetc fgetchar
*
* Although getchar and fgetchar are not specifically used in the example,
* they are equivalent to using getc or fgetc with stdin. See HEXDUMP.C
* for another example of getc and fgetc.
*/
#include <conio.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
void getword( FILE *stream, char *buf ); /* Prototypes */
void skiptoword( FILE *stream );
void main()
{
char buffer[128];
FILE *infile;
printf( "Enter file name: " );
gets( buffer );
if( (infile = fopen( buffer, "rb" )) == NULL )
{
perror( "Can't open file" );
exit( 1 );
}
/* Read each word and print reversed version. */
while( 1 )
{
skiptoword( infile );
getword( infile, buffer );
puts( strrev( buffer ) );
}
}
/* Reads one word (defined as a string of alphanumeric characters). */
void getword( FILE *stream, char *p )
{
int ch;
do
{
/* Macro version used here, but function version could be used:
ch = fgetc( stream );
*/
ch = getc( stream ); /* Get characters until EOF */
if( ch == EOF ) /* or nonalphanumeric */
exit( 0 );
*(p++) = (char)ch;
} while( isalnum( ch ) );
ungetc( ch, stream ); /* Put nonalphanumeric back */
*(--p) = '\0'; /* Null-terminate */
}
/* Throws away nondigit characters */
void skiptoword( FILE *stream )
{
int ch;
do
{
ch = getc( stream );
if( ch == EOF )
if( feof( stream ) )
exit( 0 ); /* End of file */
else if( ferror( stream ) )
exit( 1 ); /* Error */
/* else EOF character in file */
} while( !isalnum( ch ) );
ungetc( ch, stream );
}