#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;
}