C++fread/fwrite的基础用法

前言

fread是吼东西

应某人要求(大概)科普一下

fread

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define fo(a,b,c) for (a=b; a<=c; a++)
#define fd(a,b,c) for (a=b; a>=c; a--)
using namespace std;

char st[233];
char *Ch=st;

int main()
{
	fread(st,1,233,stdin);
	cout<<st<<endl;
	cout<<*Ch<<endl;
}

可以用文件输入,也可以直接输并在最后加Ctrl+Z

(下面的空行是因为读入了一个换行符)

fread基本格式:

fread(字符串,1,字符串大小,stdin);

*Ch一开始指向的是st[0],之后可以不断*++Ch来往后跳

快速读入

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define fo(a,b,c) for (a=b; a<=c; a++)
#define fd(a,b,c) for (a=b; a>=c; a--)
using namespace std;

char st[233];
char *Ch=st;

int getint()
{
	int x=0;
	
	while (*Ch<'0' || *Ch>'9') *++Ch;
	while (*Ch>='0' && *Ch<='9') x=x*10+(*Ch-'0'),*++Ch;
	
	return x;
}

int main()
{
	fread(st,1,233,stdin);
	cout<<getint()<<endl;
}

fwrite

用处并不是很大

fwrite(字符串,1,字符串长度,stdout);

快速输出

把数字转成字符串再反过来加进去(要加上空格/换行符)

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define fo(a,b,c) for (a=b; a<=c; a++)
#define fd(a,b,c) for (a=b; a>=c; a--)
using namespace std;

char st[233];
int Len;

void putint(int x)
{
	int a[233];
	int i,len=0;
	
	if (!x) len=1;
	while (x)
	{
		a[++len]=x%10;
		x/=10;
	}
	
	fd(i,len,1)
	st[++Len]=a[i]+'0';
	st[++Len]=' ';
}

int main()
{
	Len=-1;
	putint(1);
	putint(2);
	putint(233);
	
	fwrite(st,1,Len,stdout);
}

真正的fread/fwrite

其实上面的都是假的
但是上面的很好写
下面的不需要额外空间,但不能关文件

#include <bits/stdc++.h>
using namespace std;

namespace io
{
	const int SIZE = 1 << 22 | 1;
	char iBuf[SIZE], *iS, *iT, c;
	char oBuf[SIZE], *oS = oBuf, *oT = oBuf + SIZE;
	#define gc() (iS == iT ? iT = iBuf + fread(iS = iBuf, 1, SIZE, stdin), (iS == iT ? EOF : *iS++) : *iS++)
	template<class I> void gi(I &x)
	{
		int f = 1;
		for(c = gc(); c < '0' || c > '9'; c = gc())
			if(c == '-') f = -1;
		for(x = 0; c >= '0' && c <= '9'; c = gc())
			x = (x << 3) + (x << 1) + (c & 15);
		x *= f;
	}
	inline void flush()
	{
		fwrite(oBuf, 1, oS - oBuf, stdout);
		oS = oBuf;
	}
	inline void putc(char x)
	{
		*oS++ = x;
		if(oS == oT) flush();
	}
	template<class I> void print(I x)
	{
		if(x < 0) putc('-'), x = -x;
		static char qu[55];
		char *tmp = qu;
		do *tmp++ = (x % 10) ^ '0'; while(x /= 10);
		while(tmp-- != qu) putc(*tmp);
	}
	struct flusher{ ~flusher() { flush(); } }_;
}

using io :: gi;
using io :: putc;
using io :: print;

int main()
{
	int x;
	gi(x);
	print(x);
	putc('\n');
	return 0;
}
posted @   gmh77  阅读(4064)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示