Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- int main( )
- {
- /* ENSURE THE DATA IS CORRECT */
- char* file_name = "text.dat";
- FILE *fin = fopen( file_name , "r" ); //fin is the file input pointer
- //make sure the file we are reading from exists
- if( !fin )
- {
- printf( "%s could not be opened.\n" , file_name );
- exit(1); //exit with an error
- }
- /* EVALUATE THE FILE */
- int newline_count=0 , char_count=0 , c; //we will store the file's character in c
- //count characters and new lines in the file
- for( c=getc(fin) ; c != EOF ; c=getc(fin) )
- {
- ++char_count;
- if( c == '\n' )
- ++newline_count;
- }
- /* COPY THE FILE'S CONTENTS, WITH NEWLINES TO A CHAR ARRAY */
- rewind(fin); //set the file pointer back to the beginning
- const int total_chars = newline_count + char_count; //number of chars in the new 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
- if( queue[i] == '\n' ) //if it is a newline, add it again
- {
- ++i;
- queue[i] = '\n';
- }
- }
- /* NOW WRITE EACH FILE FROM THE BUFFER TO THE FILE */
- fclose(fin);
- FILE *fout = fopen( file_name , "w" ); //open it to overwrite
- for( i=0 ; i<total_chars ; ++i )
- fputc( queue[i] , fout );
- fclose(fin);
- return 0;
- }
Add Comment
Please, Sign In to add comment