Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace string in file

Status
Not open for further replies.

ej2k

Programmer
Jan 3, 2001
4
GB
I have two questions:
Firstly, is it possible to replace a string in a file?

Secondly, (and linked to the first question), is it possible to manipulate some sort of cursor, in order to find this string within the file? I currently have the words in the file held in an array of pointers.

Thanks in advance,
EJ
 
Hi,

On the first question, it's certainly possible to take a given file and reconstruct it such that certain strings are replaced by others, but you have to recreate the file in the process to do so. In other words, you can't just fseek to a given place in the file and "insert" or "delete" data without overwriting wanted or leaving unwanted characters.

On the 2nd part: sure, but I'm not totally clear on what you're asking. Do you mean something as simple as moving through a file, searching for a given string?

I just wrote this up, so the possibility of errors loom:

#include <assert.h>
#include <ctype.h>
#include <stdio.h>

/* ... */

int findString(const char *fname,char *find,int ignoreCase)
{
FILE *fp;
int count=0;
int c;
char *start=find;

assert(fname!=NULL);
assert(find!=NULL);

fp=fopen(fname,&quot;r&quot;);

if (NULL==fp) {
count=-1;
} else {
while (EOF!=(c=getc(fp))) {
if (c==*find ||
(ignoreCase &amp;&amp;
(c==toupper((unsigned char)*find) ||
c==tolower((unsigned char)*find)))) {
++find;
if (*find=='\0') {
/* The end of our find string, a match! */
++count;
/* Return the pointer to the beginning of
* our find string so that we may search
* again with optimism.
*/
find=start;
}
} else {
/* Doesn't match, return our find string
* to the beginning
*/
find=start;
}
}
}
return count;
}

It returns the count of occurences of find it finds in the file fname. It does a case-insensitive comparison if the 3rd argument is non-zero. It's very simple and stupid, so one caveat is that it doesn't have cognizance of words, meaning, for example, that it would increment the count for the string &quot;the&quot; found both in the word &quot;the&quot; and the word &quot;other.&quot; This is an easy feature to add though.

HTH,

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top