c++输出文件流ofstream用法详解

目录

这里写图片描述

头文件 <fstream>包含的多个文件流类,这里列出常用的4个:

  • ifstream Input file stream class (class )链接
  • ofstream Output file stream (class )链接
  • fstream Input/output file stream class (class )链接
  • filebuf File stream buffer (class )链接

一. 输入流 ofstream 用法

输入流的继承关系:

ios_base <- ios <- ostream <- ofstream

Public member functions (1-6)

1, (constructor)
default (1) ofstream(); // 只定义不关联

initialization (2)  //关联文件filename,默认模式 ios_base::out
explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);
explicit ofstream (const string& filename, ios_base::openmode mode = ios_base::out);

copy (3)    //禁止拷贝赋值
ofstream (const ofstream&) = delete;

move (4)    //可以右值引用临时变量赋值
ofstream (ofstream&& x);
2, ofstream::open
//和第二种构造函数一样,绑定文件
void open (const   char* filename,  ios_base::openmode mode = ios_base::out);
void open (const string& filename,  ios_base::openmode mode = ios_base::out);
3, ofstream::is_open
bool is_open() const;
// 文件打开返回 true ,否则 false
4, ofstream::close
void close();
// Closes the file currently associated with the object, disassociating it from the stream.
5, ofstream::rdbuf
filebuf* rdbuf() const;
// 返回一个指针,指向 filebuf 对象,filebuf 要么通过open()和文件绑定,要么通过rdbuf()与fstream对象绑定,绑定后才能使用。

int main () {
  std::ifstream ifs ("test.txt");
  std::ofstream ofs ("copy.txt");

  std::filebuf* inbuf  = ifs.rdbuf();
  std::filebuf* outbuf = ofs.rdbuf();

  char c = inbuf->sbumpc();
  while (c != EOF)
  {
    outbuf->sputc (c);
    c = inbuf->sbumpc();
  }
  ofs.close();
  ifs.close();
  return 0;
}
6,ofstream::operator=
copy (1) //禁止copy赋值
ofstream& operator= (const ofstream&) = delete;
move (2// 可以右值引用创建对象。
ofstream& operator= (ofstream&& rhs);

Public member functions inherited from ostream (7-11)

7,std::ostream::operator<<

用法和 cout<< 一样,是写数据到文件最方便的函数,重载了常用的数据类型。

 arithmetic types (1)   
ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (long long val);
ostream& operator<< (unsigned long long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);

stream buffers (2)  
ostream& operator<< (streambuf* sb );

manipulators (3)    
ostream& operator<< (ostream& (*pf)(ostream&));
ostream& operator<< (ios& (*pf)(ios&));
ostream& operator<< (ios_base& (*pf)(ios_base&));

string数据类型,作为参数写入到ofstream,在头文件<string>
中对输出运算符重载。
std::operator<< (string)

ostream& operator<< (ostream& os, const string& str);
8,ostream::put
ostream& put (char c);
//插入字符 c 到流中
9,ostream::write
ostream& write (const char* s, streamsize n);
//从数组s中取n 个字符插入到流中
10,ostream::tellp
streampos tellp();
返回文件指针的位置, streampos 可以转为int
11,ostream::seekp
(1) 
ostream& seekp (streampos pos);
(2) 
ostream& seekp (streamoff off, ios_base::seekdir way);

//Sets the position where the next character is to be inserted into the output stream.

参数 pos 是流中的绝对位置可以转化为 int
参数 off 是偏移量,与way相关,类型是 int
参数 way 可以选下表中的任意一个常量。

valueoffset is relative to…
ios_base::begbeginning of the stream
ios_base::curcurrent position in the stream
ios_base::endend of the stream

Public member functions inherited from ios(12-14)

12,ios::good
bool good() const;
bool eof() const;
bool fail() const;
bool bad() const;

检测流的状态是否正常。当错误的状态flags (eofbit, failbit and badbit) 都没被设置的时候返回true
特定的错误状态可以用下面的函数(eof, fail, and bad)来检测。

iostate value (member constant)indicatesgood()eof()fail()bad()rdstate()
goodbitNo errors (zero value iostate)truefalsefalsefalsegoodbit
eofbitEnd-of-File reached on input operationfalsetruefalsefalseeofbit
failbitLogical error on i/o operationfalsefalsetruefalsefailbit
badbitRead/writing error on i/o operationfalsefalsetruetruebadbit
13,ios::operator!
bool operator!() const;
//Returns true if either failbit or badbit is set, and false otherwise.
// 有错误状态返回 true

// evaluating a stream (not)
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream is;
  is.open ("test.txt");
  if (!is)
    std::cerr << "Error opening 'test.txt'\n";
  return 0;
}
14,ios::operator bool
explicit operator bool() const;
C++11: Return true if none of failbit or badbit is set. false otherwise.
// 在条件语句中,无错误返回真,有错返回假。
int main () {
  std::ifstream is;
  is.open ("test.txt");
  if (is) {
    // read file
  }
  else {
    std::cerr << "Error opening 'test.txt'\n";
  }
  return 0;
}
C++ ofstream 是一个用于写入文件输出类。它是 C++ 标准库中的一部分,用于处理文件的输入和输出操作。通过 ofstream,我们可以创建并打开一个文件,并将数据写入该文件中。你可以使用 ofstream 类的成员函数来执行诸如打开文件、写入数据、关闭文件等操作。例如,你可以使用 ofstream 对象来创建一个新的文本文件,并将一些文本内容写入其中。下面是一个示例代码片段: ```cpp #include <iostream> #include <fstream> int main() { std::ofstream file("example.txt"); // 创建并打开一个名为 example.txt 的文件 if (file.is_open()) { file << "这是一个示例文本。\n"; file << "Hello, World!\n"; file.close(); // 关闭文件 } else { std::cout << "无法打开文件。\n"; } return 0; } ``` 在这个例子中,我们首先包含了 `<iostream>` 和 `<fstream>` 头文件,分别用于输入输出文件操作。然后,我们使用 `std::ofstream` 类创建了一个名为 `file` 的对象,并传递文件名 `"example.txt"` 给它,这将创建一个新的文本文件。接下来,我们使用 `<<` 运算符将文本内容写入该文件中。最后,我们调用 `close()` 函数关闭文件。 请注意,在使用 ofstream 写入文件时,如果文件不存在,则会自动创建该文件。如果文件已经存在,则会将其现有内容覆盖。如果你希望追加内容而不是覆盖文件,请使用 `std::ofstream::app` 标志来打开文件
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值