File I/O and Operations

C Language

Introduction

With file operations, you will be able to perform operations with other files. For example, you can create a new file in a folder and perform input and output operations in it. This allows your program's impact to reach beyond execution is finished.


Basic File I/O

File I/O allows your program to impact beyond execution, and is much more secure than terminal inputs. It is very similar to normal I/O with the terminal, except you will need to create a pointer that points to a file. It can also save some time for testing. Here's the basics:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  FILE *p; /*Type FILE*/
  int a=3;
  p=fopen("file_1","w"); /*You may need .txt or other suffix depend on your operation system*/
  fprintf(p,"This text is written in file_1\na=%d",a); /*fprintf is same as printf, just writes the text
into the file pointed by p*/
  fclose(p); /*Use the fclose() function to close the file after finished*/
  printf("Finished\n");
}

Terminal:

Finished

In file_1:

This text is written in file_1
a=3

As you see, the text printed with fprintf is printed in the file pointed to by the first argument. To open a file, you first need to declare a type FILE pointer. Then, use the fopen() function to open the file and points the pointer to it (fopen() returns a pointer). The first argument passed to fopen() is the name of the file (could be variable string). The second argument is the mode in which the program opens the file in. There are six main modes for opening a file:

Mode Use
"r" Opens the file for reading only. The file must exist beforehand.
"w" Creates an empty file for writing only. If file exists already, contents will be erased.
"a" Opens the file for appending (contents are not deleted and writing starts at the end). If file does not exist, a new one will be created.
"r+" Opens a file for reading and writing that starts at the beginning. File must exist.
"w+" Opens a new empty file for reading and writing. If file exists, contents will be erased.
"a+" Opens a file for appending and reading.

We previously opened the file in mode "w" for writing because we wanted to use fprintf to print contents into the file. When the fopen() function needs to create a new file, it will be named by the first argument (the string).

Last, the fclose() function was used to close the file and free all buffers. Be sure to close all files when your program is done, just like freeing your pointers.

Other File I/O Functions

There are several other C File I/O functions, in which the mainly used include fread, fwrite, fgets, fputs, fgetc, and fputc.

fread and fwrite

These functions allows a specified amount to be read or written in a file:
fread(char *str,int size,int count,FILE *f);
fwrite(char *str,int size,int count,FILE *f);

The first argument is the string to store the string (minimum size of size*count), the second is the size, and the third is how many reads/writes you want to perform, and the fourth is the file.

fgets and fputs

These functions put a string to a file, similar to fprintf and fscanf, but safer. Here are the basic formats:
fgets(char *str,int max_char,FILE *f);
fputs(char *str,FILE *f);

fputc and fgetc

These two functions put a single character to a file:
char ch=fgetc(FILE *f); fputc(char ch,FILE *f);

Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void fcpy(char *dest,char *src)
{
  FILE *d,*s;
  char ch;
  d=fopen(dest,"w");
  s=fopen(src,"r");
  while((ch=fgetc(s))!=EOF) /*EOF means End Of File, so (ch=fgetc(s))!=EOF checks if it is the 
end of the file. Notice it is a macro, not a char (no single quotations)*/
  {
    fputc(ch,d);
  }
  fputc(EOF,d);
  fclose(d);
  fclose(s);
}

int main()
{
  char *dest=malloc(sizeof(char)*20),*src=malloc(sizeof(char)*20);
  fputs("Enter destination file:",stdout); /*stdout means STanDard OUTput, which is terminal*/
  fgets(dest,20,stdin); /*stdin is also terminal*/
  *(dest+(strlen(dest)-1))='\0'; /*Strips off the newline*/
  fputs("Enter source file:",stdout);
  fgets(src,20,stdin);
  *(src+(strlen(src)-1))='\0';
  fcpy(dest,src);
}

File: file_io_sf_1

File operations is very useful in many occasions, including making impacts beyond execution, 
process larger amounts of inputted information, etc. This is the source file for the example 
in the Abacles C Programming Tutorial File I/O Lesson.

Terminal (stdin/stdout)

Enter a destination file: file_io_df_1
Enter a source file: file_io_sf_1

File: file_io_df_1

File operations is very useful in many occasions, including making impacts beyond execution, 
process larger amounts of inputted information, etc. This is the source file for the example 
in the Abacles C Programming Tutorial File I/O Lesson.

Other Functions

Other file operations functions are much less used, but can sometimes be useful. Something to note when using most of these functions is the position of your pointer to the file. When you open a file, the position is either at the beginning or end of the file (depending on the mode you open it in), and as you use these functions, the position will change and move. For example, the pointer for a file opened in mode "r" containing "This is the entire file.\n" will point to the space character after four fgetc() calls.

Function Use
feof(FILE *p) Checks if the current position of the pointer. Non-zero value is returned when EOF (the end of the file) is reached, else, zero is returned
ftell(FILE *p) Returns the position (in type long) of the pointer in the file, this return value can only be used for passing to fseek()
fseek(FILE *p,long position,int origin) Points the pointer to a given position in the file. The third parameter origin can be 0 or SEEK_SET for counting from the beginning of file, 1 or SEEK_CUR for counting from the current position, and 2 or SEEK_END for from the end (then you will need to use a negative for the second parameter)
rewind(FILE *p) Points the pointer to the beginning of the file
ferror(FILE *p) Checks if any error occurred with operations with the file. Returns 0 if no error, else a non-zero value

Practice

Write a program to delete an inputted line from a file. Print an error message if file doesn't exist or line is not found.

Debug the following program (you may have to rewrite an entire function):

#include <stdio.h>

/*Change a file to all lowercase*/
void f_lower(FILE *p)
{
  int i;
  for(i=0;*(p+i)!=EOF;i++)
   {
     if(*(p+i)>='A' && *(p+i)<='Z')
      {
        fseek(p,i+1,0);
        fputc('\b',p);
        fputc(*(p+1)+32,p);
      }
   }
}

int main()
{
  char file_name [50];
  fgets(file_name,50);
  f_lower(file_name);
}

Create a file with multiple series of numbers each separated by a space, each series takes up a line. Write a program to sort the numbers in ascending order and print results at the end of that file.

Additional practice on file I/O:

Activity 21.2

<< Previous TOC Next >>