1

When I open the temporary file I see that the word is replaced. The string in the main file is printed in the temporary file without any spaces.

How can I fix this?

while (!feof(ptr2))
{
    strcpy(string, "\0");
    fscanf(ptr2, "%s", string);
    if (!strcmp(string, word)) // If match found
        num++;

    if (strstr(string, word))
    {
        r2 = string;
        while (r1 = strstr(r2, word))
        {
            while (r2 != r1)
            {
                fputc(*r2, temp);
                r2++;
            }
            r1 = r1 + strlen(word);
            fprintf(temp, "%s", word1);
            r2 = r1;
        }
        while (*r2 != '\0') {
            fputc(*r2, temp);
            r2++;
        }
    }
    else {
        fputs(string, temp);
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 5
    See [`while (!feof(file))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). – Jonathan Leffler May 03 '17 at 15:06
  • 2
    `"%s"` skips all white space; you'll have to output white space when you want it to see it in the output. You need to think about when you want blanks and when you want newlines. – Jonathan Leffler May 03 '17 at 15:07
  • @JonathanLeffler - Is there a shorter version? (oo) – Nguai al May 03 '17 at 15:41
  • 1
    @Nguaial : Is there a shorter version of what? – Jonathan Leffler May 03 '17 at 15:43
  • @JonathanLeffler- The link you sent was a really a long read. But thanks for the link. All this time, I used while(!feof(file)){}, I didn't get any ill effects in my application. But I realize how important to know the difference. – Nguai al May 03 '17 at 15:48
  • Should the second `if` clause be inside the first `if` clause? That is what the original indentation suggested (I have fixed the indentation according to how the compiler sees it). If that is the case, where was the else part intended to belong to? – Peter Mortensen May 03 '17 at 17:09
  • 2
    @nguai: the shorter version of the link is the title — don't use `while (!feof(fp))`. – Jonathan Leffler May 03 '17 at 18:33

0 Answers0