Holla Tech - Learn

Accessing Files
 

An external file can be opened, read from, and written to in a C program. For these operations, C includes the FILE type for defining a file stream. The file stream keeps track of where reading and writing last occurred.

The stdio.h library includes file handling functions:
FILE  Typedef for defining a file pointer.

fopen(filename, mode) Returns a FILE pointer to file filename which is opened using mode. If a file cannot be opened, NULL is returned.
Mode options are:
r open for reading (file must exist)
w open for writing (file need not exist)
a open for append (file need not exist)
r+ open for reading and writing from beginning
w+ open for reading and writing, overwriting file
a+ open for reading and writing, appending to file

fclose(fp) Closes file opened with FILE fp, returning 0 if close was successful. EOF (end of file) is returned if there is an error in closing.

The following program opens a file for writing and then closes it: 

#include <stdio.h>

int main() { 
  FILE *fptr;
 
  fptr = fopen(“myfile.txt”, “w”);
  if (fptr == NULL) {
    printf(“Error opening file.”);
    return 1;
  }
  fclose(fptr);
  return 0;

 

When a string literal is used to specify a filename, the escape sequence \\ indicates a single backslash. In this program, if there is an error when opening the file, a -1 error code is returned to the system. Error handling is explained in a future lesson.

NOTE!
Closing a file when you are done using it is a good programming practice.

Reading from a File
 

The stdio.h library also includes functions for reading from an open file. A file can be read one character at a time or an entire string can be read into a character buffer, which is typically a char array used for temporary storage.

fgetc(fp) Returns the next character from the file pointed to by fp. If the end of the file has been reached, then EOF is returned.

fgets(buff, n, fp) Reads n-1 characters from the file pointed to by fp and stores the string in buff. A NULL character ‘\0’ is appended as the last character in buff. If fgets encounters a newline character or the end of file before n-1 characters is reached, then only the characters up to that point are stored in buff.

fscanf(fp, conversion_specifiers, vars) Reads characters from the file pointed to by fp and assigns input to a list of variable pointers vars using conversion_specifiers. As with scanf, fscanf stops reading a string when a space or newline is encountered.

The following program demonstrates reading from a file: 

#include <stdio.h>

int main() { 
  FILE *fptr;
  int c, stock;
  char buffer[200], item[10];
  float price;

  /* myfile.txt: Inventory\n100 Widget 0.29\nEnd of List */

  fptr = fopen(“myfile.txt”, “r”);

  fgets(buffer, 20, fptr);    /* read a line */
  printf(“%s\n”, buffer);

  fscanf(fptr, “%d%s%f”, &stock, item, &price); /* read data */
  printf(“%d  %s  %4.2f\n”, stock, item, price);

  while ((c = getc(fptr)) != EOF) /* read the rest of the file */
    printf(“%c”, c);

  fclose(fptr);
  return 0;

 

The gets() function reads up until the newline. fscanf() reads data according to conversion specifiers. And then the while loop reads one character at a time until the end of file. Checking for a problem when opening the file (a NULL pointer) was left out to shorten the example.


Writing to a File
 

The stdio.h library also includes functions for writing to a file. When writing to a file, newline characters ‘\n’ must be explicitly added.

fputc(char, fp) Writes character char to the file pointed to by fp.

fputs(str, fp) Writes string str to the file pointed to by fp.

fprintf(fp, str, vars) Prints string str to the file pointed to by fp. str can optionally include format specifiers and a list of variables vars.

The following program demonstrates writing to a file:

FILE *fptr;
char filename[50];
printf(“Enter the filename of the file to create: “);
gets(filename);
fptr = fopen(filename, “w”);

/* write to file */
fprintf(fptr, “Inventory\n”);
fprintf(fptr, “%d %s %f\n”, 100, “Widget”, 0.29);
fputs(“End of List”, fptr);

 

NOTE!
The “w” argument defines “writing mode” for the fopen function.

BACK NEXT 

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT