2012-06-26 87 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); 
}