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;
}
  • 32
    点赞
  • 189
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
### 回答1: `ofstream`是C++标准库中的一个输出文件类,用于向文件中写入数据。在C++中,对文件的输入和输出都是通过机制来完成的。`ofstream`类提供了一些成员函数,用于打开、关闭、读取和写入文件。 `ofstream`类的构造函数是`ofstream file;`,它创建了一个未绑定到任何文件的对象。我们可以使用成员函数`open()`来打开一个文件,例如`file.open("example.txt");`,其中`example.txt`是待操作的文件名。 在打开文件后,我们可以使用成员函数`write()`来将数据写入文件。`write()`函数接受两个参数,第一个参数是指向要写入数据的字符数组的指针,第二个参数是要写入的字符数。例如,`file.write(buffer, 100);`即向文件中写入100个字符。 另外,`ofstream`类还提供了成员函数`close()`,用于关闭文件。关闭文件后,我们可以对其进行其他操作,例如打开其他文件、读取文件等。 总结起来,`ofstream`是C++中用于输出文件的类,可以通过`open()`函数打开文件,使用`write()`函数将数据写入文件,使用`close()`函数关闭文件。这样我们就可以通过`ofstream`来编写程序,实现对文件的写入操作。 ### 回答2: ofstreamC++中用于输出文件的类。它属于ofstream类(output file stream),用于将数据以文本形式写入文件。 在输出文件之前,我们首先需要包含`<fstream>`头文件。 在使用ofstream类时,需要创建一个ofstream对象,然后打开一个文件来将数据写入。我们可以使用构造函数来创建一个对象,并将文件名作为参数传递给构造函数。例如:`ofstream file("filename.txt");` 这样就创建了一个名为filename.txt的文件。 我们还可以使用`open()`函数打开文件,而不是在构造函数中指定文件名。例如:`ofstream file; file.open("filename.txt");` 完成上述步骤后,我们就可以使用`<<`运算符将数据写入文件。例如:`file << "Hello World!";` 这样就将字符串"Hello World!"写入文件。 对于其他数据类型(如整数、浮点数等),我们可以使用`<<`运算符将其写入文件。例如:`file << 100;` 这样就将整数100写入文件。 当我们完成文件写入后,要记得使用`close()`函数关闭文件。例如:`file.close();` 这样就会将文件保存并关闭。 总结起来,使用ofstream输出文件时,我们需要创建一个ofstream对象,并打开一个文件。然后,我们可以使用`<<`运算符将数据写入文件。最后,使用`close()`函数关闭文件。这样就能够成功输出文件编码。 ### 回答3: ofstreamC++标准库中的一个类,它用于进行文件输出操作。在使用ofstream进行文件输出时,我们需要先打开一个文件来进行操作。 要使用ofstream类进行输出操作,我们首先需要在程序中包含头文件<fstream>,然后使用ofstream关键字定义一个输出文件对象。我们可以通过构造函数来创建ofstream对象,并指定需要打开的文件名。例如: ```cpp #include <fstream> int main() { ofstream outputFile("output.txt"); // 使用outputFile进行输出操作 // ... outputFile.close(); // 关闭文件 return 0; } ``` 在上面的例子中,我们创建了一个名为outputFile的ofstream对象,并将其与文件output.txt关联。接下来,我们可以使用outputFile进行输出操作,例如使用"<<"运算符将数据写入文件。完成操作后,我们使用close()函数关闭文件。 使用ofstream进行文件输出时,它所使用的编码方式与文件的打开方式有关。如果我们使用二进制方式打开文件,那么数据将按照二进制方式进行输出,即原封不动地将数据写入文件。而如果我们使用文本方式打开文件,数据将按照文本格式进行输出,即字符数据按照编码方式进行转换后再写入文件。 总而言之,ofstream可以用于将数据输出文件中,我们可以使用它进行文件的写入操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值