通过使用get()复制文件来获取垃圾值

Getting a junk value from copying a file using get()

本文关键字:文件 获取 复制 get      更新时间:2023-10-16

所以我编写了一些代码,这些代码将通过打开要复制的文件,然后使用char使用get复制char来复制文件。代码是:

int main(int argc, char* argv[]) {
    if (argc != 3) {
        cout << "ERROR: Invalid number of arguments.n";
        return 1;
    }
    ifstream inputFile(argv[1]);
    ofstream outputFile(argv[2]);
    char c;
    if (inputFile.is_open() && outputFile.is_open()) {
        while (!(inputFile.eof())) {
            c = inputFile.get();
            outputFile << c;
        }
    }
    else {
        cout << "Unable to open file(s).n";
        return 1;
    }
    inputFile.close();
    outputFile.close();
    return 0;
}

它完美地复制了文本,除了总有一个垃圾字符。(注意:我知道有更好的方法复制文件,但是我必须使用get())。

循环应该像这样:

for (int c; (c = inputFile.get()) != EOF; )
{
    if (!outputFile.put(c))
    {
        // fatal: write error, die
    }
}