I/O File Operations – Opening, Closing, Reading, Writing

Opening a File

Before using a data File in a program, we must have to open it. Opening a File establish a link between the program and the operating system. This provides the operating system; the name of the file, data structure and mode in which the file is to be opened (reading or writing and in text mode or binary mode). The File name is String of valid characters that contains two parts i.e. file name and an optional period with extensions e.g. prg1, text.txt, data.doc etc.

The data structure of a file is defined as FILE which is present in stdio.h. Before using this file we must specify the mode also for the types of operations performed on the file. The general form of declaring and opening a file is: –

Declaring File Pointer with ,

FILE *fp;

Where FILE is the data structure included in stdio.h and fp is file pointer which pointer to the start of the file. Opening a file with,

fp = fopen ("filename", "mode");

Where fp is pointer to structure of type FILE.

Writing to a file

Before writing to a File we must have to open it in write mode. The general form of the function which is used to write one character at a time in file is: fputc (ch, fp);

Where ch is a character variable or constant and fp is a file pointer.

//Write on character at time into a disk file
#include<stdio.h>
#include<conio.h>
void main()
{
  FILE *fp;
  char ch;
  clrscr();
  fp = fopen("test1.dat", "w");
  if (fp == NULL)
  {
    printf("\n Can not open file");
    exit(1);
  }
  printf("\n Type a line of text and press Enter key \n");
  while ( (ch = getche() ) != '\r')
        fputc (ch, fp);
  fclose(fp);
}

Output

Type a line of next and press Enter key 
C is a middle level language because it has the features of high
level as well as low level language.

Reading Data

The data which is written into a file, can also be read from the same file while using fgetc() function, whose general syntax is given below: –

ch = fgetc(fp);

Where ch is a character variable and fp is a file Pointer.

fgetc() function is used to read one character at a time from file to which fp is pointing. It gives either the read character or end of file (EOF) character if end of file is reached. EOF is also present in <stdio.h> file.

Closing a File

When you have finished you work of reading data from or writing data onto a file, the file must be closed. The file can be closed by using library function fclose(). The general form of closing a file is: –

fclose(fp);

where fp is a file pointer associated with a file which is to be closed. It is good programming practice to close a file as soon as processing is completed. If you do not close a file immediately after writing new data to it, it is possible that new data may be lost if the electricity goes off or the computer encounters an error.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top