Guest User

Untitled

a guest
Jul 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main( )
  5. {
  6. /* ENSURE THE DATA IS CORRECT */
  7. char* file_name = "text.dat";
  8. FILE *fin = fopen( file_name , "r" ); //fin is the file input pointer
  9.  
  10. //make sure the file we are reading from exists
  11. if( !fin )
  12. {
  13. printf( "%s could not be opened.\n" , file_name );
  14. exit(1); //exit with an error
  15. }
  16.  
  17.  
  18. /* EVALUATE THE FILE */
  19. int newline_count=0 , char_count=0 , c; //we will store the file's character in c
  20.  
  21. //count characters and new lines in the file
  22. for( c=getc(fin) ; c != EOF ; c=getc(fin) )
  23. {
  24. ++char_count;
  25. if( c == '\n' )
  26. ++newline_count;
  27. }
  28.  
  29.  
  30. /* COPY THE FILE'S CONTENTS, WITH NEWLINES TO A CHAR ARRAY */
  31. rewind(fin); //set the file pointer back to the beginning
  32. const int total_chars = newline_count + char_count; //number of chars in the new file
  33. char queue[ total_chars ]; //we will add all chars to the end of this variable
  34. int i=0; //tracks where the end of the queue is
  35.  
  36. for( i=0 ; i<total_chars ; ++i )
  37. {
  38. queue[i] = getc(fin); //add the next character in the file to the end of the queue
  39. if( queue[i] == '\n' ) //if it is a newline, add it again
  40. {
  41. ++i;
  42. queue[i] = '\n';
  43. }
  44. }
  45.  
  46.  
  47. /* NOW WRITE EACH FILE FROM THE BUFFER TO THE FILE */
  48. fclose(fin);
  49. FILE *fout = fopen( file_name , "w" ); //open it to overwrite
  50. for( i=0 ; i<total_chars ; ++i )
  51. fputc( queue[i] , fout );
  52. fclose(fin);
  53.  
  54. return 0;
  55. }
Add Comment
Please, Sign In to add comment