ifstream写入txt文件
时间: 2023-12-22 07:54:46 浏览: 45
ifstream是用于读取文件的流,如果要写入文件,应该使用ofstream。以下是一个将数据写入txt文件的示例代码:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile;
outfile.open("example.txt"); // 打开文件
// 写入数据
outfile << "Hello World!" << endl;
outfile << "This is a test." << endl;
outfile.close(); // 关闭文件
return 0;
}
```
在上述代码中,我们首先使用ofstream来创建一个输出文件流outfile,并使用open函数打开名为example.txt的文件。然后,我们使用<<运算符将数据写入文件,最后使用close函数关闭文件。
相关问题
c++ 读写txt文件
读取txt文件:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inputFile("input.txt"); // 打开文件
string line;
if (inputFile.is_open()) { // 判断文件是否成功打开
while (getline(inputFile, line)) { // 逐行读取
cout << line << endl; // 输出每行文本
}
inputFile.close(); // 关闭文件
} else {
cout << "Unable to open file" << endl;
}
return 0;
}
```
写入txt文件:
```cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("output.txt"); // 打开文件
if (outputFile.is_open()) { // 判断文件是否成功打开
outputFile << "Hello World!" << endl; // 写入文本
outputFile.close(); // 关闭文件
} else {
cout << "Unable to open file" << endl;
}
return 0;
}
```
注意:读取和写入文件时,需要使用文件流对象来操作文件,并且需要进行文件是否成功打开的判断。
ifstream 创建文件
ifstream是C++中用于输入文件流的类。它可以用来打开并读取文件的内容。在使用ifstream创建文件时,需要提供文件名和打开模式。常见的打开模式有in(表示以读取模式打开文件)和out(表示以写入模式打开文件)。如果文件不存在,ifstream会返回一个错误码。因此在使用ifstream创建文件之前,可以使用条件语句来判断文件是否成功打开。
例如,以下是使用ifstream创建文件的示例代码:
```cpp
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("example.txt"); //以读取模式打开example.txt文件
if (file) { //判断文件是否成功打开
std::cout << "文件创建成功" << std::endl;
//可以在这里进行文件的读取操作
} else {
std::cout << "文件创建失败" << std::endl;
}
return 0;
}
```
在这个例子中,我们使用ifstream打开了名为example.txt的文件。如果文件存在并且成功打开,我们会收到一条"文件创建成功"的消息。否则,我们会收到一条"文件创建失败"的消息。使用ifstream创建文件时,需要确保文件名正确且文件存在,以及程序有足够的权限来进行文件的读取操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [fstream、ifstream、ofstream创建新文件](https://blog.csdn.net/hcf999/article/details/77864456)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]