C++ 文件读写

普通文件

首先引入头文件 #inlcude <fstream>,这个头文件里包含ifstream 和 ofstream。

代码示例:
#inlcude <fstream>
char* fileName = "input.txt";
// 构造函数打开, 只读模式
std::ifstream ism(fileName, std::ios::in);
// or
//成员函数打开
std::ifstream ism;
ism.open(fileName, std::ios::in);

if (!ism){
    std::cout << "Open file failed!" << std::endl;
}
// 只读并追加模式打开文件
std::ofstream osm("target.txt", std::ios::out | std::ios::app);
    
std::string s;
 while(ism >> s){
     std::cout << s << std::endl;
     osm << s << std::endl;
 }
 
 ism.close();
 osm.close();

二进制文件

如果是二进制文件,需要使用二进制模式,即ios::binary
ifstream 拥有 read 成员函数,其原型为:
basic_istream& read (char_type* __s, streamsize __n);
ofstream 拥有 write 成员函数,其原型为:
basic_ostream& write(const char_type* __s, streamsize __n);

代码示例:
//Person 为一个类,相对于将 Person 类序列化存储
Person* p1 = new Person("daming", 14);
Person* p2 = new Person("laoA", 17);

std::ofstream osm = std::ofstream("target", std::ios::out| std::ios::binary);
    
osm.write((char*)p1, sizeof(Person));
osm.write((char*)p2, sizeof(Person));
osm.close();
std::ifstream ism = std::ifstream("target", std::ios::in | std::ios::binary);
Person p3, p4;
ism.read((char*)&p3, sizeof(Person));
ism.read((char*)&p4, sizeof(Person));
ism.close();

模式一览

除了上文中用到的ios::inios::outios::appios::binary模式之外,还有其他一些模式,列在下表

模式含义
ios::in打开文件用于读取
ios::out打开文件用于写入
ios::app追加模式,所有写入都追加到文件末尾
ios::binary二进制方式
ios::ate文件打开后定位到文件末尾。
ios::trunc如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0

文件位置指针

istream 和 ostream 定义了重新定位文件位置指针的成员函数,可以从文件的指定位置开始读取文件。

seekg(“seek get”) 定义在 ifstream 中,seekp(“seek put”)定义在 ofstream 中。它们的参数通常是一个长整型。第二个参数可以用于指定查找方向。查找方向可以是 ios::beg(默认)或是 ios::cur(从流的当前位置开始定位),或是 ios::end。

// 接上文代码示例,可以跳过第一个人,而直接从文件中读取第二个人的信息。
ism.seekg(sizeof(Person));
ism.read((char*)&p4, sizeof(Person));

附录:
Person 类的简单实现:
Person.h

//

#ifndef PERSON_H
#define PERSON_H

#include <iostream>

class Person{
    int age;
    char* name;
public:
    Person(){}
    Person(char* name, int age):name(name), age(age){}
    
    void show();
};

#endif /* PERSON_H */

Person.cpp

#include "Person.h"

void Person::show(){
        std::cout << name << " " << age << std::endl;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值