Processing the Content of Files

Processing characters within a file.

Setup input and output files:-
     ifstream file_in ("myInputFile.txt");
     if (!file_in)
          cout << "unable to access input file\n";
          exit (1);
     ofstream file_out ("myOutputFile.txt");
     if (!file_out)
          cout << "unable to access output file\n";
          exit (1);
Go through the file, process it and output it:-
      while (file_in)
          file_in.get (ch);
                  process characters
          file_out.get (ch);
Close files:-

Processing lines and words in a file.

To set the program to the start of the file:

     if ( fseek( my_file, 0, 0 ) !=0 )
          printf( "Can't move pointer to start." );

To read a line having a maximum number of characters given in constant LINE_SIZE:

     fgets( line_read, LINE_SIZE-1, my_file );

To read in words on a line:

     sscanf( line_read, "%s %s %s etc.", first_word, second_word, third_word etc. );

String Operation Example:
  To find word "begin" at the start of a line in a file called masterpiece:

     if ( fseek( masterpiece, 0, 0 ) !=0 )    /* Goto to start of file */
          printf( "Can't move pointer to start." ); return;

     while( found_flag == 0 )
          fgets(line_read, LINE_SIZE-1 ,masterpiece);
          sscanf(line_read, "%s", first_word);       /* Take first word */
          if (( strcmp ( first_word, "begin" ) == 0 ) || ( strcmp( first_word, "BEGIN" ) == 0 ))
               found_flag = 1;

Allocate Memory for a Buffer

You need to allocate memory when copying data to a buffer or you will copy data to a null pointer.
To copy a string to a buffer:
     char *buffer;
     buffer = new char[50];             // Allocate some memory for the buffer.
     strcpy(buffer, "Hello there.");

C & C++ index

Main index

To add an entry or request an existing one to be altered, please click here.

(c) Compiled by A J & B V Wood.

 Main Index