next up previous contents index
Next: Miscellaneous Up: Some hilights of the Previous: Reading and Writing: the   Contents   Index


Reading and Writing: disk files

Writing and reading to disk files is accomplished in much the same way as reading and writing to the screen. The approach taken in C is to associate a stream with the file using fopen, and then use fprintf and fscanf for reading and writing. These behave exactly like printf and scanf except that they allow you to specify which stream they operate on (printf always uses stdout, while scanf uses stdin). When you have finished using the stream you should close it with fclose.


fopen

fopen opens a file and associates a stream with it. (Declared in stdio.h.)

  
FILE *fopen(char *path, char *mode);
path is a string specifying the name of the file, while mode is a string indicating how the file is to be opened, typically either "r" to read from the file or "w" to write to it. If the file cannot be opened for some reason, fopen returns NULL.

  
FILE *my_file;
/* .. */
my_file = fopen("datafile.txt", "r");  /*  open datafile.txt for reading  */
if (my_file == NULL) {
  fprintf(stderr, "Can't open datafile.txt for reading");
  exit(1);
}
The stream may be access via fprintf or fscanf, and should be subsequently closed with fclose. (In windows programs, HaltCL should be used instead of exit.)


fclose

fclose closes a stream previously opened with fopen. (Declared in stdio.h.)

  
int fclose(FILE *stream);
A simple use of fclose might look like

  
FILE *my_file;
/* .. */
my_file = fopen("datafile.txt", "r");  
/* .. */
fclose(my_file);


fprintf

fprintf is the analogue of printf for use with arbitrary streams. (Declared in stdio.h.)

  
int fprintf(FILE *stream, const char *format, ... );
For example, to open a disk-file and write some text to it:

  
FILE *my_file;
int i;
/* .. */
my_file=fopen("datafile.txt","w");
fprintf(my_file, "i=%d", i);
/* .. */
fclose(my_file);
The meaning of the second and subsequent arguments to fprintf are described in printf.


fscanf

fscanf is the analogue of scanf for use with arbitrary streams. (Declared in stdio.h.)

  
int fscanf(FILE *stream, const char *format, ... );
For example, to open a disk-file and read some text from it:

  
FILE *my_file;
int i;
/* .. */
my_file=fopen("datafile.txt","r");
fscanf(my_file, "%d", &i);  /*  read an integer from the file into i  */
/* .. */
fclose(my_file);
For a description of the meaning of the second and subsequent arguments, see scanf.


next up previous contents index
Next: Miscellaneous Up: Some hilights of the Previous: Reading and Writing: the   Contents   Index
CATAM admin 2010-02-23