关于文件处理复制数据从一个文本文件到另一个文本文件 [英] question about file handling copy data from one text file to another

查看:192
本文介绍了关于文件处理复制数据从一个文本文件到另一个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main()
{
    clrscr();
    char ch;
    ifstream infile;
    ofstream outfile;
    infile.open("edf.txt");

    outfile.open("ew.txt");

    while(!infile.eof())
    {
        infile.get(ch);
        outfile.put(ch);
    }

    infile.close();
    outfile.close();
}



以上代码从edf.txt文件中读取数据并将其复制到ew.txt文件中


The above code reads data from edf.txt file and copy it into ew.txt file

edf.txt                             ew.txt


aliahmed                             aliahmed
ffff                                  ffffÿ



我的问题是复制额外字符ÿ是附加什么是这个字符以及如何删除它


my question is that after copy extra character ÿ is append what is this character and how i remove it

推荐答案

你还应该测试 ifstream 读完角色后立即,即

You should also test the ifstream immediately after reading the character, namely
//..
infile.get(ch);
if ( infile.good() ) outfile.put(ch);
// ..





请参阅示例代码 [ ^ ]。


之前的解决方案虽然完全正确,但并不能解释为什么第二次测试是必要的。以下是完整的故事:



在您阅读了流的最后一个字符后,

The previous solution, although entirely correct, does not explain why that second test is necessary. Here is the full story:

After you have read the last character of the stream by
infile.get (ch);



流在文件结束状态尚未。所以下一个循环迭代仍然会发生。只有在尝试读取流结束之后才会设置流中的eof标志。在最后一次迭代中,其中get命中文件结尾,ch将被设置为值EOF而不是有效字符。那个EOF值(通常是-1)就是你在输出中看到的。



实际上你可以用这样的一个测试编写你的循环:


the stream is not yet in the end-of-file state. So the next loop iteration will still occur. Only after get attempts to read beyond the stream end the eof flag in the stream will be set. In that last iteration, in which get hits the end-of-file, ch will be set to the value EOF instead a valid character. And that EOF value (usually a -1) is what you see in your output.

In fact you could have written your loop with only one test like this:

while (true)
{
    infile.get (ch);
    if (!infile.good())
        break;
    outfile.put (ch);
}


这篇关于关于文件处理复制数据从一个文本文件到另一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆