c++ 读写文件示例代码
时间: 2023-02-18 09:20:40 浏览: 55
示例代码如下:
f = open("文件名", "r")
# 打开文件,"r"表示只读模式
data = f.read()
# 读取文件内容
f.close()
# 关闭文件
f = open("文件名", "w")
# 打开文件,"w"表示写入模式
f.write("要写入的内容")
# 写入文件内容
f.close()
# 关闭文件
相关问题
c++文件读写示例代码
以下是一个简单的 C++ 文件读写示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 打开文件
ofstream outFile("example.txt");
if (!outFile.is_open()) {
cout << "无法打开文件!" << endl;
return 1;
}
// 写入文件
outFile << "这是一个示例文件。" << endl;
outFile << "我正在学习文件读写。" << endl;
// 关闭文件
outFile.close();
// 读取文件
ifstream inFile("example.txt");
if (!inFile.is_open()) {
cout << "无法打开文件!" << endl;
return 1;
}
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
// 关闭文件
inFile.close();
return 0;
}
```
这个程序首先创建一个名为 example.txt 的文件,并向其中写入两行文本。然后它打开同一个文件,读取其中的每一行,并将其打印到控制台上。最后,文件被关闭并程序结束。
c++读写文件的完整代码
以下是一个简单的 C++ 读写文件的完整代码示例:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// 写文件
ofstream fout("example.txt"); // 打开文件
if (fout.is_open())
{
fout << "Hello, C++ file I/O!" << endl; // 写入数据
fout.close(); // 关闭文件
}
else
{
cout << "Unable to open file for writing!" << endl;
return 1;
}
// 读文件
ifstream fin("example.txt"); // 打开文件
if (fin.is_open())
{
string line;
while (getline(fin, line)) // 逐行读取
{
cout << line << endl; // 输出到控制台
}
fin.close(); // 关闭文件
}
else
{
cout << "Unable to open file for reading!" << endl;
return 1;
}
return 0;
}
```
该示例中,首先使用 `ofstream` 对象打开文件进行写操作,写入数据后再关闭文件。然后使用 `ifstream` 对象打开同一文件进行读操作,逐行读取数据并输出到控制台,最后关闭文件。请注意,如果文件无法打开,则会输出错误信息并退出程序。