//////////////////////////////////////////////////////////////////////////////// // file : replace.C // // string replacement utility // // Author Date Description // ------ ---- ----------- // S. Johnson 2/22/97 Creation // //////////////////////////////////////////////////////////////////////////////// #include #include #include #include int bIgnore_Case = 0, bVerbose = 0, iOriginal_Length = 0, iNew_Length = 0; //////////////////////////////////////////////////////////////////////////////// void fnUsage() { cout << "Usage: replace [options] 'original string' 'new string' file \n" << "Options:\n" << " -i ignore case\n" << " -v verbose\n" << "Example: replace 'iNumber' 'iCount' *.C\n"; exit(1); } // end fnUsage() //////////////////////////////////////////////////////////////////////////////// void fnReplace(char *pchFilename, char *pchOriginal_String, char *pchNew_String) { { // begin local ifstream ifsInput(pchFilename); if (!ifsInput) return; ofstream ofsOutput("___temp_file___"); char szLine_Buffer[4096]; int iFound = 0; while (ifsInput.getline(szLine_Buffer, sizeof(szLine_Buffer))) { char *pchPosition = szLine_Buffer, *pchCurrent = szLine_Buffer; while ((pchPosition = strstr(pchPosition, pchOriginal_String)) != 0) { iFound++; // write leading up to replacement string while (pchPosition != pchCurrent) { ofsOutput << *pchCurrent; pchCurrent++; } // end while // write new data ofsOutput << pchNew_String; // adjust position pchCurrent = pchPosition += iOriginal_Length; if (!(*pchCurrent)) break; } // end while ofsOutput << pchCurrent << '\n'; } // end while if (bVerbose) cout << "Replaced " << iFound << " occurances in file " << pchFilename << endl; } // end local rename("___temp_file___", pchFilename); } // end fnReplace(); //////////////////////////////////////////////////////////////////////////////// void main(int argc, char *argv[]) { if (argc < 4) fnUsage(); // cycle through arguments int iIndex = 1; for (; iIndex < argc; iIndex++) { // options if (argv[iIndex][0] == '-') { switch (argv[iIndex][1]) { case 'i' : bIgnore_Case++; break; case 'v' : bVerbose++; break; default : fnUsage(); } // end switch } // end if else break; } // end for // make sure there are enough parameters if ((argc -3) < iIndex) fnUsage(); // store string info char *pchOriginal_String = argv[iIndex++], *pchNew_String = argv[iIndex++]; iOriginal_Length = strlen(pchOriginal_String); iNew_Length = strlen(pchNew_String); while (iIndex < argc) fnReplace(argv[iIndex++], pchOriginal_String, pchNew_String); } // end main