home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / io1.cpp < prev    next >
C/C++ Source or Header  |  1993-04-05  |  2KB  |  89 lines

  1. // C++ program that demonstrates sequential file I/O
  2.  
  3. #include <iostream.h>
  4. #include <fstream.h>
  5. #include <string.h>
  6.  
  7. enum boolean { false, true };  
  8.  
  9. const unsigned LINE_SIZE = 128;
  10. const unsigned NAME_SIZE = 64;
  11.  
  12. void trimStr(char* s)
  13. {
  14.   int i = strlen(s) - 1;
  15.   // locate the character where the trailing spaces begin
  16.   while (i >= 0 && s[i] == ' ')
  17.     i--;                                                 
  18.   // truncate string
  19.   s[i+1] = '\0';
  20. }
  21.  
  22. void getInputFilename(char* inFile, fstream& f) 
  23. {                
  24.   boolean ok;         
  25.   
  26.   do {
  27.     ok = true;
  28.     cout << "Enter input file : ";
  29.     cin.getline(inFile, NAME_SIZE);
  30.     f.open(inFile, ios::in);
  31.     if (!f) {
  32.       cout << "Cannot open file " << inFile << "\n\n";
  33.       ok = false;
  34.     }
  35.   } while (!ok);
  36.  
  37.  
  38. void getOutputFilename(char* outFile, const char* inFile, 
  39.                        fstream& f)
  40. {                
  41.   boolean ok;          
  42.             
  43.   do {
  44.     ok = true;
  45.     cout << "Enter output file : ";
  46.     cin.getline(outFile, NAME_SIZE);
  47.     if (stricmp(inFile, outFile) != 0) {
  48.       f.open(outFile, ios::out);
  49.       if (!f) {
  50.         cout << "File " << outFile << " is invalid\n\n";
  51.         ok = false;
  52.       }
  53.     }
  54.     else {
  55.       cout << "Input and output files must be different!\n";
  56.       ok = false;
  57.     }
  58.   } while (!ok);
  59. }
  60.  
  61. void processLines(fstream& fin, fstream& fout)
  62.   char line[LINE_SIZE + 1];
  63.  
  64.   // loop to trim trailing spaces
  65.   while (fin.getline(line, LINE_SIZE)) {
  66.     trimStr(line);
  67.     // write line to the output file
  68.     fout << line << "\n";
  69.     // echo updated line to the output window
  70.     cout << line << "\n";
  71.   }
  72.  
  73. }
  74. main()
  75. {
  76.  
  77.   fstream fin, fout;
  78.   char inFile[NAME_SIZE + 1], outFile[NAME_SIZE + 1];
  79.  
  80.   getInputFilename(inFile, fin);
  81.   getOutputFilename(outFile, inFile, fout);
  82.   processLines(fin, fout);
  83.   // close streams
  84.   fin.close();
  85.   fout.close();
  86.   return 0;
  87. }