newbie555
newbie555

Reputation: 487

weird symbol getting appended at the end

I am trying to read characters from a file and writing them to another. The problem is, though everything is being written, a weird symbol is getting appended in the next line of write file. My code is:

#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>

using namespace std;

int main(){

    FILE *f, *g;
    int ch;
    f = fopen("readfile", "r");
    g = fopen("writefile", "w");
    while(ch != EOF){
            ch = getc(f);
            putc(ch, g);
    }
    fclose(f);
    fclose(g);
return 0;
}

What may be the reason for that?

Upvotes: 0

Views: 159

Answers (3)

Alex
Alex

Reputation: 7838

The weird symbol is the EOF constant.

ch = getc(f); // we've read a symbol, or EOF is returned to indicate end-of-file
putc(ch, g); // write to g whether the read operation was successful or not

The fix is

ch = getc(f);
while (ch != EOF)
{
    putc(ch, g);
    ch = getc(f);
}

Upvotes: 1

Jared Kipe
Jared Kipe

Reputation: 1187

Think about what happens if you check the return value of getc() AFTER already using that return value.

// simple fix
ch = getc(f);
while (ch != EOF) {
    putc(ch, g);
    ch = getc(f);
}

Upvotes: 1

Gustav Larsson
Gustav Larsson

Reputation: 8487

It's because you write ch to the other file before you check if it's EOF, so that one gets written too.

Upvotes: 2

Related Questions