2012-06-26 53 views
0

我想从文件中读取字符,并将它们写入另一个。问题是,尽管所有内容都正在写入,但在下一行写入文件中会添加一个奇怪的符号。我的代码是:奇怪的符号被追加到底

#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; 
} 

可能是什么原因?

+2

你能** **请只使用[fstream的(http://en.cppreference.com/w/cpp/io/basic_fstream)? – Griwes

+1

顺便说一下,您正在使用uninited变量。 –

+0

我发起到零,仍然发生错误 – newbie555

回答

2

这是因为您在将ch写入其他文件之前,请检查它是否为EOF,以便您也可以编写它。

+0

是的你是对的 – newbie555

1

想想如果您检查getc()的返回值后会发生什么情况,AFTER已经使用该返回值。

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

奇怪的符号是EOF常数。

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 

解决方法是

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