Tuesday, 20 January 2015

File Operations in C/C++ with examples

File Operations in C/Cpp with examples:

A file that represents the sequence of bytes that are stored on the disk, where the group of related data is stored.

A file is used for permanent storage of the data. In C we have some predefined file operations.
The list is shown below


Function
description
fopen()
Tis function creates a new file or open a existing file
fclose()
This function is used to close a file
getc()
This function is used to read a character from a file
putc()
This function is used to write a character to a file
fscanf()
This function is used to read a set of data from a file
fprintf()
This function is used to write a set of data to a file
getw()
This function is used to read a integer from a file
putw()
This function is used to write a integer to a file
fseek()
This function is used to set the position to desire point
ftell()
This function is used to give the current position in the file
rewind()
This function is used to set the position to the beginning point

For fopen function we have different types of mode available to open the file, Please see the below list


Mode
Description
r
opens an text file for reading mode
w
opens or create a text file for writing mode.
a
opens a text file in append mode
r+
opens a text file in both reading and writing mode
w+
opens a text file in both reading and writing mode
a+
opens a text file in both reading and writing mode
rb
opens an binary file for reading mode
wb
opens or create a binary file for writing mode
ab
opens a binary file in append mode
rb+
opens a binary file in both reading and writing mode
wb+
opens a binary file in both reading and writing mode
ab+
opens a binary file in both reading and writing mode

Let us see the complete program that will perform all the file operations.
Header file of the class

#ifndef _IO_FILE_H_
#define _IO_FILE_H_
#include <stdio.h>
#include "AVI2SQLDTypes.h"
#include "AVI2SQLStrFuns.h"
class IOFile
{
public:
             /* This is the default constructor of
                the clas used to initialize all the
                member variables of the class */ 
           IOFile  ();
              /* Parametrized constructor of the class accepting
                 file name and mode of operation. This constructor
                 calls the Open function to open the file. */
           IOFile (CChar* pszFNAME, CChar* pszMODE);
    /* This is the destructor of the class used
       to destroy the memory allocated for
       the member variables of the class */
  virtual ~IOFile ();
   /* This function opens the given file with mode given */
  _BOOL Open (CChar *pszFNAME, CChar *pszMODE);
    /* This function closes the opened file */
  _BOOL Close ();
    /* This function reads upto uiBlocks
       of uiSize bytes from the opened file. */
  UInt32 Read (void *pBuffer, UInt32 uiSize, UInt32 uiBlocks);
    /* This function writes upto uiBlocks
       of uiSize bytes to the file */
  UInt32 Write (void *pBbuffer, UInt32 uiSize, UInt32 uiBlocks);
    /* This function moves the file pointer to the specified
       location from the origin.
       The origin should be:
         SEEK_CUR (1) - from the current position
         SEEK_END (2) - from the end of the file
         SEEK_SET (0) - from the begining of the file
    */
  _BOOL Seek (long lOffset, UInt8 ucOrig);
    /* This function returns the current file position */
  long Tell ();
    /* This function returns the file size on the disk */
  long Size ();
    /* This function tests the end-of-file. Returns CASM_TRUE if
       the file pointer reached end of the file. Otherwise CASM_FALSE
       will be returned. */
  _BOOL Eof ();
    /* This function tests for the error on the file opened */
  long Error ();
  /* This function flushes the buffered data on the file opened */
  _BOOL Flush ();
    /* This function returns the next character from the input
       stream and increments the file position indicator.*/ 
  int GetC ();
    /* This function writes the given character to the file at the current
      position and increments the file pointer position */
  _BOOL PutC (UChar ucC);
  /* This function reads one line of data from the file at a time. */
  char* ReadLine ();
    /* This function writes one line of data into the file at a time. */
  size_t  WriteLine (CChar* pszLne);
protected:
  char* m_pchFNAME;  /* name of the file including
                        absolute path to be opened. */
  FILE* m_ocFILE;  /* Handle to the file streem on the disk */
};
#endif _IO_FILE_H_
This is the implementation of the IOFile
#include "stdafx.h"
#include <assert.h>
#include "IOFile.h"
IOFile::IOFile () : m_ocFILE (NULL), m_pchFNAME (NULL)
  { }
IOFile::IOFile (CChar* pszFNAME, CChar* pszMODE)
{
  /* Ensure that pszName & pszMode should not be null */
  assert (pszFNAME == NULL); assert (pszMODE == NULL);
  /* open the file */
  Open (pszFNAME, pszMODE); 
}
IOFile::~IOFile ()
  { Close (); } /* Close the opened file */
_BOOL IOFile::Open (CChar *pszFNAME, CChar* pszMODE)
{
   char *pszFN = NULL;
  /* Open the file */
  m_ocFILE = fopen (pszFNAME, pszMODE);
  if (m_ocFILE == NULL) {
    /* if the file is not opened. try
       converting the filename to lowercase */
    pszFN = StrLower (pszFNAME);
    m_ocFILE = fopen (pszFN, pszMODE);
    free (pszFN); pszFN = NULL;
    if (m_ocFILE == NULL)
      { return _FALSE; }
  }
  /* save the file name */
  m_pchFNAME = Strdup (pszFNAME);
  return _TRUE;
}
_BOOL IOFile::Close ()
{
  int iErr = 0;
  /* close the file */
  if ((m_ocFILE))
    { iErr = fclose (m_ocFILE); m_ocFILE = NULL; }
  /* Free the memory */
  if (m_pchFNAME)
    { free (m_pchFNAME); m_pchFNAME = NULL; }
  return (_BOOL) (iErr == 0);
}
UInt32 IOFile::Read (void *pBuff, UInt32 uiSize, UInt32 uiBlocks)
{
  if (!m_ocFILE)
    { return 0; }
  return (UInt32)fread (pBuff, uiSize, uiBlocks, m_ocFILE);
}
UInt32 IOFile::Write (void *pBuff, UInt32 uiSize, UInt32 uiBlocks)
{
  if  (!m_ocFILE)
    { return 0; }
  return (UInt32)fwrite (pBuff, uiSize, uiBlocks, m_ocFILE);
}
UInt32 IOFile::WriteLine (CChar* pchLine)
{
  UInt32 uiLen = 0;
  char* pszBuffer  = NULL;
  uiLen = Strlen (pchLine);
  if  (!m_ocFILE) 
    { uiLen = 0; return uiLen; }
  /* Write the line to file */
  uiLen = (UInt32)fwrite (pchLine, 1, uiLen, m_ocFILE);
  return uiLen;
}
_BOOL IOFile::Eof ()
{
  if (!m_ocFILE)
    { return _TRUE; }
  return (_BOOL) (feof (m_ocFILE) != 0);
}
long IOFile::Error ()
{
 if (!m_ocFILE)
    { return -1; }
  return ferror (m_ocFILE);
}
_BOOL IOFile::Flush ()
{
  if (!m_ocFILE)
    { return _FALSE; }
  return (_BOOL)(fflush (m_ocFILE) == 0);
}
_BOOL IOFile::PutC (unsigned char ucC)
{
  if (!m_ocFILE)
    { return _FALSE; }
  return (_BOOL)(fputc (ucC, m_ocFILE) == ucC);
}
int IOFile::GetC ()
{
  if (!m_ocFILE)
    { return EOF; }
  return getc(m_ocFILE);
}
_BOOL IOFile::Seek (long lOffset, UInt8 ucOrig)
{
  if (!m_ocFILE)
    { return _FALSE; }
  return (_BOOL)(fseek (m_ocFILE, lOffset, ucOrig) == 0);
}
long IOFile::Tell ()
{
  if (!m_ocFILE)
    { return 0; }
  return ftell (m_ocFILE);
}
long IOFile::Size ()
{
 if (!m_ocFILE)
    { return -1; }
  long lPos, lSize;
  /* current file pointer position */
  lPos = ftell (m_ocFILE);
  /* Move to end of the stream */
  Seek (0, SEEK_END);
  /* Get size */
  lSize = Tell ();
  /* reposition pointer */
  Seek (lPos,SEEK_SET);
  /* return file length */
  return lSize;
}
char* IOFile::ReadLine ()
{
  if (!m_ocFILE)
    { return NULL; }
  /* iterator and length of the line */
  UInt32 iIndex = 0, uiLen = 256;
  char chChar; /* temp character read from file */
  /* allocate memory for line */
  char* pchLine = (char*)malloc (uiLen);
  /* read character by character from the file and save
     output line */
  while ((chChar = fgetc (m_ocFILE)) != '\n' && !Eof ()) {
    /* reallocate memory if required */   
    if (iIndex == (uiLen - 2))
      { uiLen += 128; pchLine = (char*)realloc (pchLine, uiLen); }
 if(!(chChar == ' '))
 {
    pchLine [iIndex] = chChar;
    iIndex++; 
 }
  }
  if (iIndex == 0 && Eof ()) {
    if(pchLine)
   { free (pchLine); pchLine = NULL; } } /* end of file reached return NULL */
    else {
      /* ignore line-feed character */
      if (pchLine [iIndex - 1] == 13)
     { pchLine [iIndex - 1] = '\0'; }
      else                           
        { pchLine [iIndex] = '\0'; }
  }
  /* return output line */
  return pchLine;
}


NOTE: These are the mandatory steps we need to follow while doing file operations.
We have to close the opened file, otherwise the file pointer is still in the state of open, we cannot use the same pointer for other file operations.
We need to delete the file pointer when we allocate the memory for the file pointer using the dynamic memory allocation.

No comments: