c++文件的读取和写入txt
时间: 2023-08-21 08:06:29 浏览: 51
要在 C++ 中读取和写入文本文件,可以使用标准库中的文件流(fstream)类。以下是一个例子:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 打开文件
ofstream outfile("example.txt");
// 写入数据
outfile << "Hello, world!" << endl;
// 关闭文件
outfile.close();
// 重新打开文件
ifstream infile("example.txt");
// 读取数据
string line;
getline(infile, line);
// 输出数据
cout << line << endl;
// 关闭文件
infile.close();
return 0;
}
```
这个程序会先创建一个名为 example.txt 的文件,并写入一行数据。然后重新打开该文件并读取数据,最后输出读取到的数据。
需要注意的是,在使用文件流类读取和写入文件时,需要确保文件存在并且有读写权限。
相关问题
c++读取和写入txt
文件的Python代码示例:
读取txt文件:
```python
with open("file.txt", "r") as f:
content = f.read()
print(content)
```
上面的代码使用了`with open`语句打开文件,指定文件名为`file.txt`,并使用`r`模式读取文件。读取的内容被保存在`content`变量中,并使用`print`函数输出。
写入txt文件:
```python
with open("file.txt", "w") as f:
f.write("Hello, world!")
```
上面的代码使用了`with open`语句打开文件,指定文件名为`file.txt`,并使用`w`模式写入文件。写入的内容为`Hello, world!`。
c++文件的读取和写入
要在C++中读取和写入文件,可以使用C++标准库中的fstream头文件。
读取文件:
使用ifstream来打开文件,并读取文件中的内容。
示例代码:
```cpp
#include <iostream>
#include <fstream>
int main() {
std::ifstream input_file("input.txt");
if (input_file.is_open()) {
std::string line;
while (std::getline(input_file, line)) {
std::cout << line << std::endl;
}
input_file.close();
}
return 0;
}
```
这段代码打开了名为"input.txt"的文件,并将文件中的每一行打印到控制台上。
写入文件:
使用ofstream来打开文件,并将内容写入文件中。
示例代码:
```cpp
#include <iostream>
#include <fstream>
int main() {
std::ofstream output_file("output.txt");
if (output_file.is_open()) {
output_file << "Hello, world!" << std::endl;
output_file.close();
}
return 0;
}
```
这段代码创建了一个名为"output.txt"的文件,并将"Hello, world!"写入文件中。