Wednesday, August 4, 2010

FILE COPY CODE (CP cmd in Unix) basic version of CP command

/*    Basic FILE COPY FUNCTION IN UNIX SIMILAR TO CP COMMAND  */


#include
#define MAX_LINE_LEN 1000      /* maximum line length supported. */
void main(int argc, char* argv[])
{
      char* filePathFrm;
      char* filePathTo;
      FILE* fFrm;
      FILE* fTo;
      char buf[MAX_LINE_LEN+1];
      filePathFrm = "";
      filePathTo = "";
      fFrm = fopen(filePathFrm, "r");
      if (!fFrom) 

      {
        // Print log or some exception handling
            perror("source Fileopen failed:");
            exit(1);
      }
      f_to = fopen(file_path_to, "w+");
       if (!f_to)
       {
         // Print log or some exception handling
          perror("destination fileopen failed:")
          exit(1);
       }
         /* Copy source to target, line by line. */
     while (fgets(buf, MAX_LINE_LEN+1, f_from))
     {
         if (fputs(buf, f_to) == EOF)
          {
                    exit(1);
           }
     }
     if (!feof(f_from))
     {
       
         exit(1);
     }
     if (fclose(f_from) == EOF)
     {
        exit(1);
      }
     if (fclose(f_to) == EOF)
     {
        exit(1);
     }
     return(0);
}


NOTE:
  •  fopen() function shall open the file whose pathname is the string pointed to by filename, and associates a stream with it.returnvalue:Pointer to the opened files object.on failure it returns NULL
  •  fclose() function causes the stream pointed to by stream to be flushed and the associated file to be closed . returnvalue:  0on succes. Otherwise, it returns EOF.
  • feof() function tests the end-of-file indicator for the stream pointed to by stream. returnvalue: non-zero if and only if the end-of-file indicator is set for stream
  • perror():The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message.returnvalue:no return value
        

No comments:

counter