File RW (파일 읽고 쓰기)

2014. 1. 20. 21:51Programing/C Language

/***************************************************************************
                 COPYRIGHT(c) 2010 XXX Co., Ltd.
****************************************************************************
*
*  Workfile   : FileRW.c
*  Revision   : Rev. 0.1
*  Date       : Mon 06.14.2010, 12:11:00
*  Author     : Victor
*
****************************************************************************
*
* File Description
* ----------------
* This file is source file for "File Read".
*
****************************************************************************
*
* Revision Details
* ----------------
* Rev. 0.1   Initial revision.
*
***************************************************************************/

#ifndef _FILE_READWRITE_
#define _FILE_READWRITE_

/***************************************************************************
 * Include Files
 **************************************************************************/
#include stdio.h>
#include stdlib.h>
#include io.h>

void  InputPath   (char ** ppPath                );
void  DisplayFile (FILE *  fOpen                 );
void  Malloc      (char ** ppParameter, int nSize);

/***************************************************************************
 *  Macros
 **************************************************************************/
// Safe free
#define RELEASEIF( a )           if(a){free(a); a=NULL;}

//===========================================================================
// DESCRIPTION
//  Main funtion
//
// PARAMETERS
//    none
//===========================================================================
void main()
{
   FILE * fOpen;
   char * pPath    = NULL;

   Malloc(&pPath, 100);

   InputPath(&pPath);

   fopen_s(&fOpen, pPath, "rb");

   if( NULL == fOpen )
   {
      printf("File read failed!!\n");
      return;
   }
   else
   {
      printf("File read success!!\n");
      printf("File read: \n");
      DisplayFile(fOpen);
   }

   printf("\n\nRead End!!!\n");

   fclose(fOpen);

   RELEASEIF(pPath);
}

void InputPath(char ** ppPath)
{
   printf ("Please, Input your file path : ");
   scanf_s("%[^\n]", (* ppPath));

   printf("\nYour input path is ""%s""\n\n", (* ppPath));
}

void DisplayFile(FILE * fOpen)
{
   char * pBuffer  = NULL;
   long   nLength  = 0;

   nLength = _filelength(_fileno(fOpen));
   printf("Size : %ld Byte\n", nLength);

   Malloc(&pBuffer, nLength);

   printf("\n________________________________________\n");
   while(!feof(fOpen))
   {
      while(fgets(pBuffer, nLength, fOpen) != NULL)
      {
         printf("%s", pBuffer);
      }
   }
   printf("\n________________________________________\n");

   RELEASEIF(pBuffer);
}

void Malloc(char ** ppParameter, int nSize)
{
   (* ppParameter) = (char *)malloc(nSize);

   if((* ppParameter) == NULL)
   {
      printf("Malloc is failed!!\n");
      return;
   }

   memset((* ppParameter), 0, nSize);
}
 
#endif //_FILE_READWRITE_