home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
OS/2 Shareware BBS: 10 Tools
/
10-Tools.zip
/
cenvi23.zip
/
TREPLACE.CMM
< prev
next >
Wrap
Text File
|
1995-10-02
|
3KB
|
98 lines
// TReplace.cmm - Text replace. Replace text in a file.
// ver.1
Instructions()
{
puts("TReplace.cmm: Text replace. Replace text in a file.\a")
puts(``)
puts(`USAGE: CEnvi TReplace <filespec> <oldtext> <newtext>`)
puts(``)
puts(`WHERE: filespec - File specification for any text-mode file`)
puts(` oldtext - Any text to find in lines of filespec`)
puts(` newtext - New text to replace found old text`)
puts(``)
puts(`NOTE: This search is case-sensitive and slow, with very few options,`)
puts(` But the Cmm code is very simple.`)
puts(``)
puts(`EXAMPLE: CEnvi TReplace c:\autoexec.bat F:\UTL\CENVID F:\UTL\CENVIW`)
puts(``)
exit(EXIT_FAILURE);
}
#define TEMP_FILE_NAME "TREPLACE.TMP"
main(argc,argv)
{
if ( 4 != argc )
Instructions();
// Get input parameters
FileSpec = argv[1];
OldText = argv[2];
NewText = argv[3];
// Open old source file
SrcFP = fopen(FileSpec,"rt");
if ( !SrcFP ) {
printf("Unable to open source file \"%s\" for reading.\n\a",FileSpec);
exit(EXIT_FAILURE);
}
// open temporary file in same directory as source file
FileNameParts = SplitFileName(FileSpec);
sprintf(TemporaryFileSpec,"%s%s",FileNameParts.dir,TEMP_FILE_NAME);
DstFP = fopen(TemporaryFileSpec,"wt");
if ( !DstFP ) {
printf("Unable to open temporary file \"%s\" for reading.\n\a",TemporaryFileSpec);
fclose(SrcFP);
exit(EXIT_FAILURE);
}
// replace all text in source
TextReplaced = WriteWithReplace(SrcFP,DstFP,OldText,NewText);
// not reading or writing any more, so close files
SrcError = ferror(SrcFP) & fclose(SrcFP);
DstError = ferror(DstFP) & fclose(DstFP);
// if error in either file then say so
if ( SrcError ) {
printf("Error reading source file \"%s\".\a\n",FileSpec);
} else if ( TextReplaced ) {
// text was replaced so remove old file and replace with new one
if ( DstError )
printf("Error writing temporary file \"%s\".\a\n",TemporaryFileSpec);
else if ( remove(FileSpec) )
printf("Unable to remove old file \"%s\" for replacing.\n\a",FileSpec);
else if ( rename(TemporaryFileSpec,FileSpec) )
printf("Unable to replace old file with new file. Old file \"%s\"\n"
"may be lost!\a\n",FileSpec);
else
printf("Replace %d \"%s\" with \"%s\".\n",TextReplaced,OldText,NewText);
} else {
puts("No text replaced.");
}
// whatever else may have happened, delete temporary file if there
remove(TemporaryFileSpec);
}
WriteWithReplace(src,dst,find,replace)
{
lCount = 0;
FindLen = strlen(find);
ReplaceLen = strlen(replace);
while( lFound = lLine = fgets(src) ) {
while ( lFound = strstr(lFound,find) ) {
lCount++;
strcpy(lFound+ReplaceLen,lFound+FindLen);
memcpy(lFound,replace,ReplaceLen);
lFound += ReplaceLen;
}
fputs(lLine,dst);
}
return lCount;
}