2013-02-17 118 views
1

我正嘗試使用原始I/O函數從文件讀取並將數據輸出到另一個文件 但是,似乎我的代碼無法工作,我想通過它是read()不能被終止。不過,我不知道該如何終止循環的情況下,我的代碼是這樣的:如何停止從二進制文件中讀取c

int main(){ 
    int infile; //input file 
    int outfile; //output file 

    infile = open("1.txt", O_RDONLY, S_IRUSR); 
    if(infile == -1){ 
     return 1; //error 
    } 
    outfile = open("2.txt", O_CREAT | ORDWR, S_IRUSR | S_IWUSR); 
    if(outfile == -1){ 
     return 1; //error 
    } 

    int intch; //character raed from input file 
    unsigned char ch; //char to a byte 

    while(intch != EOF){ //it seems that the loop cannot terminate, my opinion 
     read(infile, &intch, sizeof(unsigned char)); 
     ch = (unsigned char) intch; //Convert 
     write(outfile, &ch, sizeof(unsigned char)); 
    } 
    close(infile); 
    close(outfile); 

    return 0; //success 
} 

有人能幫助我的問題嗎?謝謝你很多

回答

1

read將返回0如果遇到文件的末尾:

while(read(infile, &intch, sizeof(unsigned char) > 0){ 
    ch = (unsigned char) intch; //Convert 
    write(outfile, &ch, sizeof(unsigned char)); 
} 

注意,負值表示錯誤,所以你可能要保存的read回報。

+0

是的你是對的,我真的應該仔細閱讀手冊!非常感謝 – 2013-02-18 00:18:07

+0

@Zeta ..感謝您早些時候糾正我的迴應.. + 1爲您的迴應:) – Ganesh 2013-02-18 00:23:05

0

intch是未初始化的4(或有時8)個字節。您只能將1個字節裝入intch中,並將剩餘的字節保留爲未初始化狀態。然後,您將EOF與所有尚未完全初始化的intch進行比較。

嘗試將intch聲明爲char。

+0

是的,你指出我的另一個問題非常感謝。 – 2013-02-18 01:21:31