gpt4 book ai didi

c++ - 将文本从一个文件复制到另一个文件

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:21 24 4
gpt4 key购买 nike

我尝试了两种不同的 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.\n\n";
exit(1);
}

cout << "\nThe file has been successfully opened for reading.\n\n";


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.\n\n";


//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() 来检查是否已到达文件末尾。

关于c++ - 将文本从一个文件复制到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com