| |
FILE
*file_ptr; /* declare a file pointer variable */
Recommended way to open a file -
if ( (file_ptr = fopen("Filename.dat","rt+"))
== NULL )
{ printf("Error opening
file\n");
exit(1);
}
Reading from
the file -
int fgetc ( FILE
*stream );
/* Returns EOF on end of file or an error occurs */
eg. my_char = fgetc( file_ptr );
char *fgets ( char *str, int number, FILE *stream );
/* Returns EOF on end of file or an error occurs */
eg. fgets( my_string, 80, file_ptr);
int fscanf ( FILE *stream, char *conversion_string, arg_list);
/* Returns the
number of successful conversions */
eg. fscanf ( file_ptr , "%d %d %d", &int1, &int2,
&int3);
Writing to
the file -
int fputc ( int character,
FILE *stream );
/* Returns char written or EOF on error */
eg. fputc( 'A' , file_ptr );
int fputs (char *str, FILE *stream );
/* Returns zero value on success, non zero on error */
eg. fputs( "Hello world\n", file_ptr);
int fprintf ( FILE *stream, char *conversion_string, arg_list);
/* Returns
the number of characters printed */
eg. fprintf ( file_ptr , "%d %d %d", &int1, &int2,
&int3);
Checking if
an error occurred during a read/write -
int ferror ( FILE *stream
);
/* Returns zero if no error, non zero on error */
eg. if (ferror(file_ptr)) /* an error occurred */
Clear a buffer associated with a stream -
int fflush( FILE *stream );
eg. fflush(stdin); /*Clears input buffer*/
Closing the
file after use -
fclose( FILE *stream );
eg. fclose (file_ptr);
|
|