Creating files in C++(在 C++ 中创建文件)
问题描述
我想用 C++ 创建一个文件,但我不知道该怎么做.例如,我想创建一个名为 Hello.txt
的文本文件.
I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt
.
有人可以帮我吗?
推荐答案
一种方法是创建 ofstream 类的一个实例,并使用它来写入您的文件.这是一个网站链接,其中包含一些示例代码,以及有关大多数 C++ 实现可用的标准工具的更多信息:
One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:
ofstream 参考
为了完整起见,这里有一些示例代码:
For completeness, here's some example code:
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
您想使用 std::endl 来结束您的行.另一种方法是使用 ' ' 字符.这两件事是不同的, std::endl 刷新缓冲区并立即写入您的输出,而 ' ' 允许输出文件将所有输出放入缓冲区,并可能稍后写入.
You want to use std::endl to end your lines. An alternative is using ' ' character. These two things are different, std::endl flushes the buffer and writes your output immediately while ' ' allows the outfile to put all of your output into a buffer and maybe write it later.
这篇关于在 C++ 中创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中创建文件


基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01