//------------------------------------------------------------------------
//  change.cpp
//  This program replaces all occurrences of one string with another
//  string within a text file.  The user is prompted for the file name,
//  the old string, and the new string.
//  The old and new strings must be the same length.
//------------------------------------------------------------------------
#include <iostream.h>
#include <fstream.h>
#include <string.h>    // For strlen() and strcmp()

const int MAX_LEN = 100;    // Max. length of search string

int main()
{
    char fName[51];             // Assume file name is at most 50 chars

    cout << "File name: ";
    cin >> fName;
    cin.ignore(100, '\n');      // Eat newline

    fstream theFile(fName, ios::in | ios::out | ios::nocreate);
    if ( !theFile ) {
        cerr << "Can't open file\n";
        return 1;
    }

    char      oldStr[MAX_LEN+1];
    char      newStr[MAX_LEN+1];
    char      fileStr[MAX_LEN+1];
    int       strLength;
    streampos savedPos = 0;       // Last search position

    cout << "Old string (max. 100 chars): ";
    cin.get(oldStr, MAX_LEN+1);             // Don't skip whitespace
    cin.ignore(100, '\n');                  // Eat newline

    cout << "New string (same length as old string): ";
    cin.get(newStr, MAX_LEN+1);

    strLength = strlen(oldStr);
    if (strLength != strlen(newStr)) {
        cerr << "Strings not the same length\n";
        return 1;
    }

    while (theFile.get(fileStr, strLength+1))  // Read strLength chars

        if (strcmp(fileStr, oldStr) == 0) {
            // ASSERT: Old string is found
            theFile.seekp(savedPos);        // Move the put-pointer
            theFile << newStr;              // Overwrite old string
            savedPos = theFile.tellg();     // Continue input at
                                            //    current position
        }
        else {
            savedPos++;
            theFile.seekg(savedPos);    // Retreat to previous
        }                               //    search position + 1
    return 0;
}

