01 文件操作
流操作
std::ifstream
#include <fstream> #include <iostream> #include <string> int main () { std::string filename = "Test.b" ; double d = 3.14 ; std::ofstream (filename, std::ios::binary) .write (reinterpret_cast <char *>(&d), sizeof d) << 123 << "abc" ; std::ifstream istrm (filename, std::ios::binary) ; if (!istrm.is_open ()) std::cout << "failed to open " << filename << '\n' ; else { double d; istrm.read (reinterpret_cast <char *>(&d), sizeof d); int n; std::string s; if (istrm >> n >> s) std::cout << "read back from file: " << d << ' ' << n << ' ' << s << '\n' ; } }
std::ofstream
#include <fstream> #include <iostream> #include <string> int main () { std::string filename = "Test.b" ; { std::ofstream ostrm (filename, std::ios::binary) ; double d = 3.14 ; ostrm.write (reinterpret_cast <char *>(&d), sizeof d); ostrm << 123 << "abc" << '\n' ; } std::ifstream istrm (filename, std::ios::binary) ; double d; istrm.read (reinterpret_cast <char *>(&d), sizeof d); int n; std::string s; istrm >> n >> s; std::cout << " read back: " << d << ' ' << n << ' ' << s << '\n' ; }
std::fstream
#include <fstream> #include <iostream> #include <string> int main () { std::string filename{ "test.bin" }; std::fstream s{ filename, s.binary | s.trunc | s.in | s.out }; if (!s.is_open ()) std::cout << "failed to open " << filename << '\n' ; else { double d{ 3.14 }; s.write (reinterpret_cast <char *>(&d), sizeof d); s << 123 << "abc" ; s.seekp (0 ); d = 2.71828 ; s.read (reinterpret_cast <char *>(&d), sizeof d); int n; std::string str; if (s >> n >> str) std::cout << "read back from file: " << d << ' ' << n << ' ' << str << '\n' ; } }
文本模式与二进制模式
文本模式:将数据转成字符串,再输出
二进制模式:直接输出数据的二进制
例如:123 int
文本模式输出是“123”。
二进制模式输出是0x0000007B。也就是int类型在本系统里,内存的直接布局输出。
<<与write
write是将数据直接以二进制输出,给定数据的起始地址和大小。
<<是将数据以文本格式输出,会将数据格式化为字符串然后输出。
>>与read
read是将数据直接以二进制读入,给定buffer和大小。
>>
是将数据以文本格式输入,会将文件中的数据以字符的形式读入,然后根据给定类型进行转换。
文件位置指示器(File Position Indicator)
案例:获取文件大小
#include <fstream> #include <iostream> int main () { std::ifstream file ("example.txt" , std::ios::binary) ; if (file) { file.seekg (0 , std::ios::end); std::streampos size = file.tellg (); std::cout << "File size: " << size << " bytes" << std::endl; file.close (); } else { std::cerr << "Unable to open file." << std::endl; } return 0 ; }
练习
传入一个文件名,获取文件的信息,列出来
参考资料