C++文件的随机读写与特定格式输入输出

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;

int main(void) {
	string filename = "Test.txt";
	ofstream outfile;
	//打开文件
	outfile.open(filename);
	//判断文件是否打开
	if (!outfile.is_open()) {
		cout << "文件打开失败" << endl;
		return 1;
	}
	int c=0;
	int n = 10000;
	while (n--) {
		//向outfile中写入数据
		outfile << c++;
	}
	//01234567891011................................

	//seekg(参数1,参数2)
	//作用:设置输入流的位置
	//参数1:偏移量  
    //参数2:起始位置{.beg 开始,  .cur 当前,  .end 结束}
	outfile._Seekbeg(0, outfile.end);//输入流当前位置在末尾

	//tellp()
	//作用:返回当前输入流的位置

	int size = outfile.tellp();//用于计算文件的字节大小

	//stringstream
	//作用:使用特定的格式输出
	stringstream ss;
	ss << "FileName:" << filename << "\t" << "文件大小:" << size<<" 字节";
	//.str()进行格式转换
	cout << ss.str() << endl;

	/*
	//使用c语言可以实现特定格式的输入: 
	//string name;//c语言不支持string
	char name[32];
	int age;
	sscanf_s("姓名:%s 年龄:%d", name, sizeof(name), &age);
	*/


	//.seekp(参数1,参数2)
	//作用:设置输出流的位置
	//参数1:偏移量
	//参数2:起始位置 (同seekg)
	outfile.seekp(0, outfile.beg);//输出流位置处于开始
	outfile << "ABC";//ABC34567891011...........................

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值