- 一、二进制读写
- 二、文件打开模式
- 三、随机访问文件
一、二进制读写
#include#include #include #include namespace fs = std::filesystem; int main() { namespace fs = std::filesystem; using io = std::ios; fs::path p{ "array.dat" }; //创建二进制输出流 std::fstream out{ p,io::out | io::app }; //判断流是否成功打开 省略 //将一个整形数组的内容输出到二进制文件中 std::array a{ 21L,42L,63L }; std::streamsize size = a.size() * sizeof(a[0]); out.write(reinterpret_cast (&a[0]), size); //以读取模式重新打开二进制文件,或者将文件光标定位到文件头fsteam::seekg() out.close(); out.open(p, io::in); //从二进制流中读入一个整数并显示到品目撒谎那个 auto x{ 0L }; out.read(reinterpret_cast (&x), sizeof(x)); std::cout << x << std::endl; std::cin.get(); return 0; }
结果如上图所示。
#include#include #include namespace fs = std::filesystem; int main() { using fo = std::ios; fs::path p1{ "city1.txt" }, p2{ "city.txt" }; //创建两个输出文件流,分别为app和trunc模式 std::ofstream out1{ p1,fo::out | fo::app }; //追加模式 std::ofstream out2{ p2,fo::out | fo::trunc }; //trunc 每次打开会清除内容 //从键盘读入字符,输出到两个文件流中 char c; while (!std::cin.get(c).eof()) { out1.put(c); out2.put(c); } //关闭文件流 out1.close(); out2.close(); //读模式打开两个IO文件流,期中一个使用ate模式 std::fstream in1{ p1,fo::in }; std::fstream in2{ p2,fo ::in | fo::ate }; //ate模式,每次打开,光标放在最后 //输出两个文件的内容 std::cout << p1 << std::endl; while (!in1.get(c).eof()) { std::cout << c; } std::cout << p2 << std::endl; while (!in2.get(c).eof()) { std::cout << c; } //关闭IO文件流 in1.close(); in2.close(); std::cin.get(); return 0; }
注意这里需要ctrl+z 结束输入。
#include#include #include #include #include namespace fs = std::filesystem; using std::wcout; using std::endl; using std::fstream; int main() { //任务1:在文件中存2个long long int 和“hello world”字符串 fs::path p{ "test.dat" }; fstream file{ p,std::ios::out | std::ios::in | std::ios::trunc }; auto x{ 12LL }, y{ 24LL }; char str[]{ "Hello World" }; file.write(reinterpret_cast (&x), sizeof(x)); file.write(reinterpret_cast (&y), sizeof(long long int)); file.write(str, sizeof(str)); //任务2:从文件中读取Hello字符串 char buf[100]{ 0 }; file.seekg(2 * sizeof(long long int), std::ios::beg); file.read(buf, 5); std::cout << buf << std::endl; return 0; }
结果如上图所示。



