#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;
}
C++文件的随机读写与特定格式输入输出
最新推荐文章于 2023-09-04 20:41:15 发布