一文说完c++全部基础知识,IO流(二)

一、IO流

流、一连串连续不断的数据集合。



看下图,继承关系

using namespace









流类的构造函数

eg:ifstream::ifstream (const char* szFileName, int mode = ios::in, int);

c 复制代码
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream inFile("c:\\tmp\\test.txt", ios::in);
    if (inFile)
        inFile.close();
    else
        cout << "test.txt doesn't exist" << endl;
  
    ofstream oFile("test1.txt", ios::out);
    if (!oFile)
        cout << "error 1";
    else
        oFile.close();

    fstream fFile("tmp\\test2.txt", ios::out | ios::in);
    if (!fFile2)
        cout << "error 2";
    else
        fFile.close();
        
    return 0;
}
c 复制代码
#include <iostream>
#include <fstream>
using namespace std;
int arr[100];
int main()
{

	int num = 0;
	ifstream inFile("i.txt", ios::in);//文本模式打开
	if (!inFile)
		return 0;//打开失败
	ofstream outFile("o.txt",ios::out);
	if (!outFile)
	{
		outFile.close();
		return 0;
	}
	int x;
	while (inFile >> x)
		arr[num++] = x;
	for (int i = num - 1; i >= 0; i--)
		outFile << arr[i] << " ";
	inFile.close();
	outFile.close();
	return 0;
}

ostream::write 成员函数:ostream & write(char* buffer, int count);

c 复制代码
class Person
{
public:
	char m_name[20];
	int m_age;
};
int main()
{

	Person p;
	ofstream outFile("o.bin", ios::out | ios::binary);
	while (cin >> p.m_name >> p.m_age)
		outFile.write((char*)&p, sizeof(p));//强制类型转换
	outFile.close();
	//heiren 烫烫烫烫烫烫啼  
	return 0;
}

一个字节一个字节地读写,不如一次读写一片内存区域快。每次读写的字节数最好是 512 的整数倍

c 复制代码
#include <iostream>
#include <fstream>
//#include <vector>
//#include<cstring>
using namespace std;

class Person
{
public:
	char m_name[20];
	int m_age;
};
int main()
{


	Person p;
	ifstream ioFile("p.bin", ios::in | ios::out);//用既读又写的方式打开
	if (!ioFile) 
		return 0;
	ioFile.seekg(0, ios::end); //定位读指针到文件尾部,以便用以后tellg 获取文件长度
	int L = 0, R; // L是折半查找范围内第一个记录的序号
				  // R是折半查找范围内最后一个记录的序号
	R = ioFile.tellg() / sizeof(Person) - 1;
	do {
		int mid = (L + R) / 2; 
		ioFile.seekg(mid *sizeof(Person), ios::beg); 
		ioFile.read((char *)&p, sizeof(p));
		int tmp = strcmp(p.m_name, "Heiren");
		if (tmp == 0)
		{ 
			cout << p.m_name << " " << p.m_age;
			break;
		}
		else if (tmp > 0) 
			R = mid - 1;
		else  
			L = mid + 1;
	} while (L <= R);
	ioFile.close();

	system("pause");
	return 0;
}
相关推荐
方传旺10 分钟前
C++17 std::optional 深拷贝 vs 引用:unordered_map 查询大对象性能对比
c++
Dontla25 分钟前
Makefile介绍(Makefile教程)(C/C++编译构建、自动化构建工具)
c语言·c++·自动化
何妨重温wdys1 小时前
矩阵链相乘的最少乘法次数(动态规划解法)
c++·算法·矩阵·动态规划
重启的码农1 小时前
ggml 介绍 (6) 后端 (ggml_backend)
c++·人工智能·神经网络
重启的码农1 小时前
ggml介绍 (7)后端缓冲区 (ggml_backend_buffer)
c++·人工智能·神经网络
雨落倾城夏未凉1 小时前
5.通过拷贝构造函数复制一个对象,假如对象的成员中有个指针类型的变量,如何避免拷贝出来的副本中的该成员之下行同一块内存(等价于默认拷贝构造函数有没有缺点)
c++·后端
雨落倾城夏未凉1 小时前
4.深拷贝VS浅拷贝
c++·后端
tanyongxi662 小时前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
fqbqrr2 小时前
2508C++,支持rdma通信的高性能rpc库
c++·rpc
liulilittle3 小时前
BFS寻路算法解析与实现
开发语言·c++·算法·宽度优先·寻路算法·寻路