一遍又一遍地创建同一个文本文件

Creating the same text file over and over

本文关键字:一遍 文本 文件 同一个 创建      更新时间:2023-10-16

我需要创建一个程序,在当前文件夹中写入一个文本文件,该文本文件总是包含相同的信息,例如:

Hello,
This is an example of how the text file may look
some information over here
and here
and so on

所以我想做这样的事情:

#include <iostream>
#include <fstream>
using namespace std;
int main(){
    ofstream myfile("myfile.txt");
    myfile << "Hello," << endl;
    myfile << "This is an example of how the text file may look" << endl;
    myfile << "some information over here" << endl;
    myfile << "and here" << endl;
    myfile << "and so on";
    myfile.close();
    return 0;
}

如果我的文本文件中的行数很小,那么它就可以工作,问题是我的文本文件有超过2000行,我不愿意为每一行提供myfile << TEXT << endl;格式。

有没有更有效的方法来创建这个文本文件?谢谢。

如果在同一个文件中写入有问题,则需要使用追加模式。也就是说,你的文件必须像这样打开

ofstream myfile("ABC.txt",ios::app)

您可以在c++ 11中使用Raw字符串:

const char* my_text =
R"(Hello,
This is an example of how the text file may look
some information over here
and here
and so on)";
int main()
{
    std::ofstream myfile("myfile.txt");
    myfile << my_text;
    myfile.close();
    return 0;
}

生活例子

或者,您可以使用一些工具为您创建数组,如xxd -i

如果您不关心'n'和std::endl之间的细微差异,那么您可以在函数之外创建一个静态字符串,然后它只是:

myfile << str // Maybe << std::endl; too

如果你的文本非常大,你可以写一个小脚本来格式化它,比如用"n"来改变每一个换行符,等等

听起来你真的应该使用资源文件。我不会在这里复制粘贴所有的信息,但是在这个网站上已经有一个非常好的问题:在原生Windows应用程序的资源中嵌入文本文件

或者,你甚至可以将字符串放在头文件中,然后在需要的地方包含该头文件:(假设没有c++ 11,因为如果你有,你可以简单地使用Raw来使事情变得更简单,但是这个问题的答案已经发布了——不需要重复)。

#pragma once
#include <iostream>
std::string fileData =
    "data line 1rn"
    "data line 2rn"
    "etc.rn"
;

如果需要更复杂的字符,请使用std::wstring并在字符串前加上L。您所需要做的就是编写一个小脚本(如果是一次性的,甚至可以使用notepad++),将反斜杠替换为双反斜杠,将双引号替换为反斜杠双引号,并将换行符替换为rn"{line break}{tab}"。整理好开头和结尾,你就完成了。然后将字符串写入文件