/* 1.文件操作 这需要用到 C++ 中另一个标准库 fstream 2.对于标准库 fstream ,它定义了三个新的数据类型: 数据类型 描述 ofstream 表示输出文件流,用于创建文件并向文件写入信息 ifstream 表示输入文件流,用于从文件读取信息 fstream 表示文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息 记忆: OutFileStream --> ofstream InFileStream --> ifstream 3.打开文件 open() 函数是 fstream、ifstream 和 ofstream 对象的一个成员 e.g. void open(const char *filename, ios::openmode mode); 参数说明:(以下模式可以结合使用) ios::app 追加模式。所有写入都追加到文件末尾 ios::ate 文件打开后定位到文件末尾 ios::in 打开文件用于读取 ios::out 打开文件用于写入 ios::trunc 如果该文件已经存在,其内容将在打开文件之前被截断,即把文件长度设为 0 例如: 1.以写入模式打开文件,并希望截断文件,以防文件已存在 ofstream outfile; // 实例化一个文件对象 outfile outfile.open("file.dat", ios::out | ios::trunc ); // 调用文件对象,并使用 open 函数成员 2.打开一个文件用于读写 ifstream afile; afile.open("file.dat", ios::out | ios::in ); 4.读取文件 使用流提取运算符 >> 从文件读取信息 5.写入文件 使用流插入运算符 << 向文件写入信息 6.关闭文件( close()函数是 fstream、ifstream 和 ofstream 对象的一个成员) void close(); 7.文件位置指针 1.istream 和 ostream 都提供了用于重新定位"文件位置指针"的成员函数 istream 的 seekg() // 含义"seek get" ostream 的 seekp() // 含义"seek put" 参数:(不写参数,默认ios::beg) ios::beg // begin 从开头 开始定位 ios::cur // current 从当前位置 开始定位 ios::end // end 从末尾 开始定位 文件位置指针,是一个整数值 指定了从文件的起始位置 到指针所在位置的字节数 */
#include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // 以写模式打开文件 ofstream outfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // 向文件写入用户输入的数据 outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // 再次向文件写入用户输入的数据 outfile << data << endl; // 关闭打开的文件 outfile.close(); // 以读模式打开文件 ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // 在屏幕上写入数据 cout << data << endl; // 再次从文件读取数据,并显示它 infile >> data; cout << data << endl; // 关闭打开的文件 infile.close(); return 0; }
// 定位到 fileObject 的第 n 个字节(假设是 ios::beg) fileObject.seekg( n ); // 把文件的读指针从 fileObject 当前位置向后移 n 个字节 fileObject.seekg( n, ios::cur ); // 把文件的读指针从 fileObject 末尾往回移 n 个字节 fileObject.seekg( n, ios::end ); // 定位到 fileObject 的末尾 fileObject.seekg( 0, ios::end );
浙公网安备 33010602011771号