[ create a new paste ] login | about

Link: http://codepad.org/rrMt1G50    [ raw code | output | fork | 1 comment ]

joshua_cheek - C, pasted on Nov 30:
#include <stdio.h>
#include <stdlib.h>

//argc holds how many parameters the program received when called
//argv holds their values
int main( int argc , char const *argv[] )
{  
  /* ENSURE THE FILE NAME WAS PASSED */
  if( argc != 2 )                                   //make sure they submitted the file name we are going to copy
  {
    printf( "Please list the file name as a parameter to this program.\n" );
    exit(1);                                        //exit with an error
  }
  
  /* ENSURE THE FILE EXISTS */
  char const* file_name = argv[1];                  //use the filename passed in from the command line
  FILE *fin = fopen( file_name , "r" );             //fin is the file input pointer
  if( !fin )                                        //make sure the file we are reading from exists
  {
    printf( "%s could not be opened.\n" , file_name );
    exit(1); //exit with an error
  }
  
  
  /* EVALUATE THE FILE */
  int total_chars=0 , c;                            //we will store the file's character in c
  for( c=getc(fin)  ;  c != EOF  ;  c=getc(fin) )   //count characters and new lines in the file
    ++total_chars;
  
  
  /* COPY THE FILE'S CONTENTS, WITH NEWLINES TO A CHAR ARRAY */
  rewind(fin);                                      //set the file pointer back to the beginning of the file
  char queue[ total_chars ];                        //we will add all chars to the end of this variable
  int i=0;                                          //tracks where the end of the queue is
                                                    
  for( i=0 ; i<total_chars ; ++i )                  
    queue[i] = getc(fin);                           //add the next character in the file to the end of the queue
    
  
  /* NOW WRITE EACH CHAR FROM THE QUEUE TO THE FILE */
  fclose(fin);
  FILE *fout = fopen( file_name , "w" );            //open it to overwrite
  for( i=0  ;  i<total_chars  ;  ++i )              //for each char
  {                                                 
    fputc( queue[i] , fout );                       //copy it to the file
    if( queue[i] == '\n' )                          //if it is a newline
      fputc( '\n' , fout );                         //then copy it agian
  }
  fclose(fin);
  
  return 0;
}


Output:
1
Please list the file name as a parameter to this program.


Create a new paste based on this one


Comments:
posted by joshua_cheek on Nov 30
Doubles lines a file by reading the input file to see how many characters it will need, creates an array of that length, copies the chars from the input file into the array, then writes the array back to the file.
reply