C++读写utf-8文件
时间: 2023-07-07 18:36:11 浏览: 69
您好,以下是在 C++ 中读写 UTF-8 编码文件的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main()
{
// 以读写方式打开文件
std::fstream file("filename.txt", std::ios::in | std::ios::out);
// 检查文件是否打开成功
if (!file.is_open())
{
std::cout << "Failed to open file." << std::endl;
return 1;
}
// 读取文件内容
std::string content;
std::getline(file, content);
// 输出读取的内容
std::cout << "Read content: " << content << std::endl;
// 在文件末尾写入内容
file.seekp(0, std::ios::end);
file << "Hello, world!";
// 关闭文件
file.close();
return 0;
}
```
在这个示例代码中,我们使用了 `std::fstream` 类型的对象来打开文件,并且在打开文件时指定了 `std::ios::in` 和 `std::ios::out` 标志,表示以读写方式打开文件。在读取文件内容时,我们使用了 `std::getline` 函数来读取一行内容,并且将读取的内容保存到了一个 `std::string` 类型的变量中。在写入文件内容时,我们使用了 `std::fstream` 对象的 `seekp` 方法来将文件指针移动到文件末尾,并且使用 `operator<<` 运算符来写入内容。最后,我们使用 `close` 方法关闭了文件。
需要注意的是,在读写 UTF-8 编码文件时,可能会遇到一些编码上的问题,例如 BOM(字节顺序标记)等。如果您遇到了这些问题,可以使用一些第三方库来处理 UTF-8 编码。