将文本从一个文件复制到另一个文件

copy text from one file to another

本文关键字:文件 一个 复制 另一个 文本      更新时间:2023-10-16

我尝试了两个不同的while循环。我认为他们也有类似的问题。它们都没有终止或给出任何输出。

任务是将一个文件(逐字节)复制到另一个文件中。该文件不必有换行符,也不必是.txt文件(可以是.exe…)。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;

int main(int argc, char *argv[])
{
char c, c1, c2;
ifstream inFile;
ofstream outFile;
inFile.open("blackbird.txt");
if (inFile.fail())
{
    cout << "nThe file was not successfully opened for reading."
    << "nPlease check that the file currently exists.nn";
    exit(1);
}
cout << "nThe file has been successfully opened for reading.nn";

outFile.open("blackbird_copy.txt");
if (outFile.fail())
{
    cout << "The file was not successfully opened for writing" << endl;
    exit(1);
}
cout << "The file has been successfully opened for writing.nn";

//outFile << "Hello";
// 1) this loop doesn't terminate. 2) the computer doesn't know what c1     is.
/*
while (inFile.get(c1))
{
    outFile << c1;
    cout << c1;
}
*/

// This one is no better
/*
while (inFile.good())
{
    inFile.get(c);
    outFile << c;
}
*/

inFile.close();
outFile.close();

// read contents of blackbird_copy to check our work.
inFile.open("blackbird_copy.txt");
while (inFile.get(c2))
{
    cout << c2;
}
cout << endl << endl;
return 0;
}

inFile.get(c1)读取一个字符并将其存储到c1(如果可用)。否则,不修改ch并设置failbit和eofbit。

您可以使用inFile.eof()来检查是否已到达文件的末尾。