quest4tech.net |
|
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:-file_in.close();file_out.close(); Processing lines and words in a file.To set the program to the start of the file:
if ( fseek( my_file, 0, 0 ) !=0 )
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 */
while( found_flag == 0 )
Allocate Memory for a BufferYou 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) Compiled by A J & B V Wood. |