Replace a word in a text file, then output the overwritten version
<p>For this problem I'm asked to first read from the input text file, prompt the user which word/string to get replaced, then output the <strong>same</strong> file (the original gets overwritten). The thing is the input/outputfile name must always have a specific name for example <strong>test.txt</strong> (this is what bothers me)</p>

<p>Here's the function which I tested out and it does the job replacing, but for now I'm prompting user to enter their own "sentence" and then for words. I'm lost on how to (always) read from a <strong>test.txt</strong> and then output the same one with replaced string.</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;stdlib.h&gt;


char *w_replace(const char *s, const char *oldone, const char *newone)
{
char *ret;
int i, count = 0;
int newlen = strlen(newone);
int oldonelen = strlen(oldone);

for (i = 0; s[i] != '\0'; i++)
{
    if (strstr(&amp;s[i], oldone) == &amp;s[i])
    {
        count++;
        i += oldonelen - 1;
    }
}
ret = (char *)malloc(i + count * (newlen - oldonelen));
if (ret == NULL)
    exit(EXIT_FAILURE);
i = 0;
while (*s)
{
    if (strstr(s, oldone) == s) //compare 
    {
        strcpy(&amp;ret[i], newone);
        i += newlen;
        s += oldonelen;
    }
    else
    ret[i++] = *s++;
}
ret[i] = '\0';
return ret;
}

int main(void)
{
char mystr[100], c[10], d[10];
char fileOld[32] = "test.txt";
char fileNew[32] = "test.txt";
char word_search[80];
char word_replace[80];
FILE *fp1, *fp2;

fp1 = fopen(fileOld,"r");
fp2 = fopen(fileNew,"w");

printf("Enter the word to replace :\n");
scanf(" %s",word_search);
printf("Enter the new word:\n");
scanf(" %s",word_replace);
char *newstr = NULL;

newstr = w_replace(fileOld, word_search , word_replace);


fputs(word_replace, fp2);
fclose(fp2);
fclose(fp1);
return 0;
}
</code></pre>

<p>So if a <code>test.txt</code> contains the following sentence </p>

<pre><code>This is a test
</code></pre>

<p>Result</p>

<pre><code>Enter the word to replace :
This
Enter the new word:
That
</code></pre>

<p>The new updated <code>test.txt</code> file will only be </p>

<pre><code>That
</code></pre>

<p>instead of</p>

<pre><code>That is a test
</code></pre>