尝试学习c++中的基本文件操作

Trying to learn basic file manipulation in c++

本文关键字:文件 操作 学习 c++      更新时间:2023-10-16

我正在努力掌握在C++中处理文件的窍门。我正在尝试从一个文件中读取并制作另一个具有相同内容的文件。我已经成功地做到了可以复制文件的第一行,但不能复制其余的行。有人能告诉我我做错了什么吗?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]){
    string line;
    ofstream writeFile;
    ifstream readFile;
    readFile.open("students.txt");
    if (readFile.is_open()){
        while (getline (readFile, line)){
            writeFile.open("copytext.txt");
            writeFile << line;
            writeFile << line;
            writeFile << line;
            writeFile << line;
        }
    }
    readFile.close();
    writeFile.close();
    return 0;
}

默认情况下,如果不指定标志,则openmode将为write。这将销毁文件的内容(如果该文件已存在)。

#include <iostream>
#include <fstream>
int main()
{
    std::ofstream of("test.txt"); // close() implicitly called by destructor
}
> echo "hello" > test.txt
> cat test.txt
hello
> g++ test.cpp
> ./a.out
> cat test.txt

哎呀!

你显然应该把它移到循环之外。顺便说一句,您不需要显式调用openclose,因为构造函数和析构函数将分别调用它们。流对象也可以隐式转换为bool(如果流中有错误,则返回false),从而使is_open成为冗余。

int main(int argc, char * argv[]){
    string line;
    ifstream readFile("students.txt");
    ofstream writeFile("copytext.txt");
    if (readFile && writeFile){
        while (getline (readFile, line)) {
            writeFile << line;
        }
    }
}

根据此链接,无法再次打开同一个文件并导致失败,如设置failbit所示。所需的输出文件应该只打开一次。

我可以从您的代码重写的最简单方法

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]){
string line;
ofstream writeFile;
ifstream readFile;
readFile.open("students.txt");
writeFile.open("copytext.txt",std::fstream::out);
if (readFile.is_open()){
while (getline (readFile, line)){
    writeFile << line;

}
}
readFile.close();
writeFile.close();
return 0;
}

打开流时,您可以使用打开模式:std::fstream::in或std::fstream:

这将适用于

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]){
string line;
ofstream writeFile;
ifstream readFile;
readFile.open("students.txt");
writeFile.open("copytext.txt");
if (readFile.is_open()){
    while (getline (readFile, line))
    {       
        writeFile << line << "n";
    }
}
readFile.close();
writeFile.close();
return 0;
}

其中一个问题是您试图在while循环中打开"copytext.txt"。你还试着写了4次相同的文本,这是不必要的。