01 文件操作

01 文件操作

流操作

std::ifstream

#include <fstream>
#include <iostream>
#include <string>

int main()
{
std::string filename = "Test.b";

// prepare a file to read
double d = 3.14;
std::ofstream(filename, std::ios::binary)
.write(reinterpret_cast<char*>(&d), sizeof d) << 123 << "abc";

// open file for reading
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); // binary input
int n;
std::string s;
if (istrm >> n >> s) // text input
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); // binary output
ostrm << 123 << "abc" << '\n'; // text output
}

// read back
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
{
// write
double d{ 3.14 };
s.write(reinterpret_cast<char*>(&d), sizeof d); // binary output
s << 123 << "abc"; // text output

// for fstream, this moves the file position pointer (both put and get)
s.seekp(0);

// read
d = 2.71828;
s.read(reinterpret_cast<char*>(&d), sizeof d); // binary input
int n;
std::string str;
if (s >> n >> str) // text input
std::cout << "read back from file: " << d << ' ' << n << ' ' << str << '\n';
}
}

文本模式与二进制模式

  • 文本模式:将数据转成字符串,再输出

  • 二进制模式:直接输出数据的二进制

例如:123 int

文本模式输出是“123”。

二进制模式输出是0x0000007B。也就是int类型在本系统里,内存的直接布局输出。

<<与write

write是将数据直接以二进制输出,给定数据的起始地址和大小。

<<是将数据以文本格式输出,会将数据格式化为字符串然后输出。

>>与read

read是将数据直接以二进制读入,给定buffer和大小。

>>是将数据以文本格式输入,会将文件中的数据以字符的形式读入,然后根据给定类型进行转换。

文件位置指示器(File Position Indicator)

  • 每个文件流(如 ifstreamofstreamfstream)都有一个与之关联的文件位置指示器。这个指示器跟踪当前在文件中的位置,即下一个将被读取或写入的点。

  • 使用 tellg()(对于输入流)或 tellp()(对于输出流)来获取当前位置,也可以使用 seekg()seekp() 来移动这个指示器。

案例:获取文件大小

#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;
}

练习

传入一个文件名,获取文件的信息,列出来

  • 文件名

  • 文件大小

  • 文件内容

参考资料