- Specify a file to work with: The declaration simply sets up a file pointer.
At this point in the program, the pointers do NOT point to any file. C
requires the open function to set the pointers to a file.
FILE *ptr, *input_file;
- Open a file - a return value of NULL from the fopen() indicates that the
file could not be opened for some reason.
input_file = fopen("inputfile.dat", "r");
ptr = fopen("output_name.dat", "w");
- Close a file
fclose(input_file);
fclose(ptr);
- Read from a file
fscanf(input_file, "%d", &value);
- Write to a file
fprintf(ptr, "%d", value);
- Other read/write options for opening a file
- Determine the end of file
feof(ptr) - function that returns true when the end of the file is reached
value == EOF - EOF is the end of file marker. If I'm reading values into
value, I can check to see if I have read the end of file
marker
- Reading and writing structures - you can only use fread() on files that
have been created using fwrite(). See Foster, 10.5 for discussion and
examples.
fwrite(&value, size_of(type of value), how_many, file_ptr);
fread(&value, size_of(type of value), how_many, file_prt);