【C++文件和流】

C++ 文件和流

文件和流

  • 标准库 <fstream>
    数据类型: ofstream, ifstream, fstream

  • 打开文件 open() 函数

void open(const char *filename, ios::openmode mode);

mode为文件打开模式:
1. ios::app, 追加模式
2. ios::ate, 文件打开后定位到文件末尾
3. ios::in, 打开文件用于读取
4. ios::out, 打开文件用于写入
5. ios::trunc, 如果文件存在,内容将会在打开文件前被截断,即文件长度设为0

例: 如果想要打开一个文件用于读写

ifstream  afile;
afile.open("file.dat", ios::out | ios::in );
  • 关闭文件 close() 函数

  • 写入和读取文件 使用流插入运算符(<<) 和流提取运算符(>>)

  • 读取、写入实例

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

结果

$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
  • 文件位置指针
    istream 的 seekg("seek get")
    ostream 的 seekp("seek put")

    第二个参数可以用于指定查找方向。
    ios::beg(默认的,从流的开头开始定位)
    ios::cur(从流的当前位置开始定位)
    ios::end(从流的末尾开始定位)

// 定位到 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 );
posted @ 2021-08-30 16:42  西西果RuJ  阅读(51)  评论(0)    收藏  举报