游戏开发之C++IO流(C++基础)
2021/10/7 11:11:12
本文主要是介绍游戏开发之C++IO流(C++基础),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
游戏开发之C++IO流(C++基础)
头文件fstream:
1.文本文件
#include <iostream> #include <fstream>//C++IO流头文件 using std::cout; using std::endl; using std::cin; int main() { //文本文件读写 //std::ifstream //输入流 //std::ofstream //输出流 //std::fstream //输入输出流 std::fstream file; //打开文件 //file.open(文件名,打开模式); //以下是默认的打开模式,文件不存在则新建文件,文件存在则打开文件不清空写入。 //file.open("2.txt", std::ios::in | std::ios::out); //以下打开模式,文件存在则打开出错,用于读取数据 //file.open("2.txt",std::ios::in); //以下开始模式,文件不存在则新建文件,如果文件存在,则清空原来数据再写入,用以写入数据。 //file.open("2.txt",std::ios::out); file.open("2.txt", std::ios::in | std::ios::out); if (!file.is_open()) { file.close(); cout << "文件打开失败!" << endl; } char buffer[1024] = { 0 }; //第一种读文件方式 //file >> buffer; //第二种读取文件方式 //file.getline(buffer, 1024); //写入文件方式 //file << "你好\n"; file.close(); return 0; }
2.二进制文件
#include <iostream> #include <fstream> using std::cout; using std::endl; using std::cin; int main() { //二进制文件读写 //fstream模式下,file对象能输入也能输出 std::fstream binFile; binFile.open("3.txt", std::ios::binary | std::ios::in | std::ios::out); if (!binFile.is_open()) { binFile.close(); cout << "打开文件失败!" << endl; } //写入文件方式 int arr[10] = { 1,2,3,4,5 }; binFile.write((char *)arr, sizeof(int) * 10); //读取文件方式 int buffer[10]; //std::ios::cur 当前位置 //std::ios::beg 起点位置 //std::ios::end 终点位置 binFile.read((char *)buffer, sizeof(int) * 10); //当前位置往后(往前)偏移8个字节 binFile.seekg(-8 * (int)sizeof(int), std::ios::cur); binFile.read((char *)buffer, sizeof(int) * 5); //tellg获取当前流指针的位置 int pos = binFile.tellg(); //eof为true表示已经到文件末尾 binFile.eof(); //关闭文件 binFile.close(); return 0; }
这篇关于游戏开发之C++IO流(C++基础)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享