用C++创建文件进行数据存储和管理
一、创建文件
C++中可以使用fstream库来创建文件。该库中提供了两个类,fstream和ofstream,分别用于读写文件和写文件。fstream和ofstream都定义了open()函数,用来打开文件。如果文件不存在,则open函数会自动创建一个文件。
#include <iostream> #include <fstream> using namespace std; int main() { ofstream file("example.txt"); file.close(); return 0; }
该示例中,使用ofstream类创建了一个名为example.txt的文件并关闭了文件。
二、写入文件
使用ofstream类的 using namespace std; int main() { ofstream file("example.txt"); file #include <fstream> using namespace std; int main() { ifstream file("example.txt"); string content; getline(file, content); cout using namespace std; struct Person { string name; int age; }; int main() { ofstream file("people.txt"); Person p1 = {"John", 25}; Person p2 = {"Mary", 30}; file
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。