Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As per sharptooth's solution, I knocked up some C code to do a find and replace on a file. I used stdio calls (strlen, strstr, strcpy and strcat) to do the string manipulation (rather than win32 calls), so your only dependancy is the C run time.</p> <p>This is certainly not code I would use in a production system. I would use stuff from toolkit string manipulation libraries to make this much cleaner (and not so much with the fixed length buffers). I probably wouldn't use boost, I don't like the overhead. But I figured you might like an example with just the basics (N.B. This writes the altered buffers out to .temp).</p> <pre><code>#include &lt;stdio.h&gt; #define BUF_LEN 2048 int findAndReplace (const char * file, const char * find, const char * replace) { int replaceCount = 0; FILE * f = fopen (file, "rt"); if (strstr(replace, find)) return 0; // replacing blah with stuff_blah_stuff unsigned int findLen = strlen (find); char tempFile [BUF_LEN]; strcpy (tempFile, file); strcat (tempFile, ".temp"); FILE * writeF = fopen (tempFile, "wt"); if (!f || !writeF) return 0; printf ("Processing %s - %s to %s\n", file, find, replace); char lineBuf [BUF_LEN]; memset (lineBuf, 0, BUF_LEN); char tempLineBuf [BUF_LEN]; memset (tempLineBuf, 0, BUF_LEN); // read each line of the file while (fgets (lineBuf, BUF_LEN, f)) { // get the position of find in the line buffer char * pos = strstr (lineBuf, find); while (pos) { strncpy (tempLineBuf, lineBuf, pos - lineBuf); strcat (tempLineBuf, replace); strcat (tempLineBuf, pos + findLen); replaceCount++; // replace the current buf with the replaced buffer strncpy (lineBuf, tempLineBuf, BUF_LEN); memset (tempLineBuf, 0, BUF_LEN); pos = strstr (lineBuf, find); } printf ("writing new line %s\n", lineBuf); fputs (lineBuf, writeF); } fclose (f); fclose (writeF); return replaceCount; } int main () { printf ("Made %d replacements\n", findAndReplace ("blah.txt", "marker", "testing_blah")); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload