Colderleo's blog Colderleo's blog
首页
Linux
C++
Python
前端
工具软件
mysql
索引
关于
GitHub (opens new window)

Colder Leo

热爱代码的打工人
首页
Linux
C++
Python
前端
工具软件
mysql
索引
关于
GitHub (opens new window)
  • bug定位的一些情形
  • c++性能调优,可能的情况
  • total-编程知识点集锦
  • hpc_common.hpp
  • memory order 内存模型
  • 类型推导之auto-template-decltype
  • 完美转发forward源码分析
  • 左值和右值,右值引用、重载 std-move,引用折叠
  • cmake用法
  • alignas、alignof、sizeof实现内存对齐分配
  • 通过宏定义控制debug打印
  • 程序耗时性能测试
  • 线程池开源项目阅读
  • C++类中包含没有默认构造函数的成员
  • C++可变参数模板
  • C++属性继承 public protected private
  • C++智能指针
  • C++导出so的方法,以及extern C 注意事项
  • 四种spin lock
  • condition_variable和unique_lock
  • dpdk、kernel bypass
  • 智能网卡solarflare、Mellanox、X10等
  • 汇编寄存器和常见指令
  • c++ 类的静态成员变量未定义
  • C++获取类成员函数地址
  • preload示例
  • C++异常安全和RAII
  • C++11单例模式
  • C++歪门邪道
  • boost-program-option用法
  • c++17通过模板获取类成员的个数
  • 通过模板实现结构体成员拷贝-按成员名匹配
  • STL学习路径
  • boost库安装使用方法
  • C++文件读写
  • linux下socket通信demo,server和client
  • makefile写法
  • RxCpp
  • C++
gaoliu
2021-10-06

C++文件读写

# iostream 读二进制

//打开文件
string fileName = "test.dat"
fstream readFile;
readFile.open(fileName, ios::binary | ios::in);
if (!readFile.is_open())
{
    cout << "cannot open file : " << fileName << endl;
    //处理打开失败的情况。 这里没找到失败原因如何打印。
}

//读数据
struct stData stdata;
while (readFile.peek() != EOF)
{
    readFile.read((char*)&stdata,sizeof(stdata));
    if (readFile.gcount() < sizeof(stdata)) {
        cout << "the last data is not complete." << endl;
        break;
    }
    //处理数据
}

//关闭文件
readFile.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# FILE* 读

//打开文件
FILE* readFile;
errno_t err;
string readFileName = "test.dat";
int err = fopen_s(&readFile, readFileName.c_str(), "rb");//r表示read,b表示二进制

//检查打开错误信息
char errmsg[64];
if (err != 0) {
    strerror_s(errmsg, 64, err);
    cout << "cannot open file '" << readFileName <<"' : "<< errmsg <<endl;
    continue;
}

//读数据
struct stData *st = new stData[10];
int readNum=0;
readNum = fread(&st, sizeof(st), 10, readFile);//从readFile中读取10个stData,返回读成功的个数。

//关闭文件
fclose(readFile);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# FILE* 写

//打开文件
FILE* writeFile;
string writeFileName = "test.txt";
int err = fopen_s(&writeFile, writeFileName.c_str(), "w");

//检查打开写文件的错误信息
char errmsg[64];
if (err != 0) {
    strerror_s(errmsg, 64, err);
    cout << "cannot open write file '" << writeFileName <<"' : "<< errmsg <<endl;
    continue;
}

//写入
fprintf(writeFile, "write someting to file %d.\n", 123);

//关闭文件
fclose(writeFile);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编辑 (opens new window)
上次更新: 2023/05/07, 17:27:54
boost库安装使用方法
linux下socket通信demo,server和client

← boost库安装使用方法 linux下socket通信demo,server和client→

最近更新
01
通过模板实现结构体成员拷贝-按成员名匹配
05-07
02
c++17通过模板获取类成员的个数
05-01
03
avx-sse切换惩罚
04-30
更多文章>
Theme by Vdoing | Copyright © 2019-2023 Colder Leo | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×