有关fstream中openmode讨论【转】

  今天很恼火,是因为自己了,和上一次犯了一个同样的错误,分析出了原因但是并没有把错误记录下来,今天在这里想好好的分析一下fstream中openmode的问题,在msdn中介绍了有六种打开的方式,第一种为app我认为是单词(append)意思,感觉的英文的解释就是在在插入之前先把光标定位到文件的末尾。第二种为ate,英文的解释为to seek to the end of a stream when its controlling object is first created。第三种为binary,英文的解释为以二进制的方式去读文件,而不是以字节方式去读文件。第四种就是in从文件中读取数据。第五种就是out向文件中写入数据。第六种是trunc, to delete contents of an existing file when its controlling object is created。

eg:#include <iostream>
#include <fstream>

int main ( ) 
{
   using namespace std;
   fstream file;
   file.open( "rm.txt", ios_base::out | ios_base::trunc );

   file << "testing";
}

一下就是最好的东东了,是在msdn中找到的,是fstream::open(filename,strmode)有关几种方式的组合讨论问题,是英文的,我感觉学计算机还是多看英文的,就不再翻译了:

The member function opens the file with filename filename, by calling fopen(filename, strmode). strmode is determined from mode &

~(ate & | binary):

  • ios_base::in becomes "r" (open existing file for reading).
  • ios_base::out or ios_base::out | ios_base::trunc becomes "w" (truncate existing file or create for writing).
  • ios_base::out | app becomes "a" (open existing file for appending all writes).
  • ios_base::in | ios_base::out becomes "r+" (open existing file for reading and writing).
  • ios_base::in | ios_base::out | ios_base::trunc becomes "w+" (truncate existing file or create for reading and writing).
  • ios_base::in | ios_base::out | ios_base::app becomes "a+" (open existing file for reading and for appending all writes).

If mode & ios_base::binary is nonzero, the function appends b to strmode to open a binary stream instead of a text stream. It then stores the value returned by fopen in the file pointer fp. If mode & ios_base::ate is nonzero and the file pointer is not a null pointer, the function calls fseek(fp, 0, SEEK_END) to position the stream at end of file. If that positioning operation fails, the function calls close(fp) and stores a null pointer in the file pointer.

posted on 2011-04-23 20:03  鲁大山  阅读(2361)  评论(0编辑  收藏  举报

导航