fstream、ifstream、ofstream创建新文件

来源:互联网 发布:手游编程用什么软件 编辑:程序博客网 时间:2024/06/14 00:48

先阅读 iostream的工程实践,论述了isotream的用途与局限,与c语言io的对比(more effetive c++ item23也有论述)

关键问题1:如果文件不存在,三种流如何处理? 关键问题2:文件中已有内容,对文件读写时如何控制从何处开始?

ps1: fstream头文件不包含有ifstream和ofstream,后者不是前者的子类 

ps2: iostream头文件自动包含了istream和ostream,cin 是istream对象,cout是ostream对象

ps3: io流对象不可拷贝、赋值,fstream fs= fs1不能通过编译,它的copy ctr已经delete

ps4:流的操作是内存到流(如cout, ofstream );流到内存(如cin,ifstream) ;两个文件流之间如何输入输出暂时不知。

ps5: 打开文件——读写文件——关闭文件(用流的close函数)

ofstream: 只写模式打开文件,如果文件不存在,可以创建文件 

ofstream file("new_create.txt", fstream::out);if (file) cout << " new file created" << endl;
第二个参数为打开模式,可以不写,用默认的;要判断文件是否创建或打开成功,用上面的判断就可以;下面的open函数也可以打开文件

ofstream file1("new_2.txt");ofstream file3;//有默认构造函数file3.open("new_3.txt");if (file3.is_open()) cout << "file3  is open" << endl;
ifstream: 只读模式打开文件,如果文件不存在,不会创建,不能创建空文件读

ifstream in ("in.txt");// in.txt不存在,则打开会 if (!in) cout << "in not created" << endl; //已经存在的文件也可能打开失败,所以打开失败不一定是文件不存在
构造函数创建输出文件流

ifstream in1("new_create.txt");if (in1.is_open()) cout << "已存在的文件打开成功" << endl;
先用default ctr,再用open函数

ifstream in2;in2.open("new_2.txt");if (in2.is_open()) cout << "in2 打开成功" << endl;
fstream: 读/写模式打开文件,如果文件不存在,已只读模式打开可以创建,以读/写或写模式不能创建空文件

fstream fs("new_fs.txt", fstream::out | fstream::in); //创建不起作用if (!fs) cout << "不能以读写模式创建文件" << endl;
fstream的构造函数原型:http://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream 默认参数就是读写模式

fstream fs2("new_fs2.txt",  fstream::in);if (!fs2.is_open())  cout << "以写模式不能创建新文件" << endl;
只读模式可以创建新文件

fstream fs3("new_fs3.txt", fstream::out);if (fs3.is_open())  cout << "以只读模式能创建新文件" << endl;

下面例子的过程是 ofstream 创建新文件,写入字符串; ifstream 读取该文件,并把内容显示到屏幕;fstream打开已存在的文件进行读写

//写模式cout << "hcf.txt不存在" << endl;ofstream outfile("hcf.txt");if (outfile.is_open()) cout << "hcf.txt被创建" < endl;string s = "perfect is shit";outfile << s << endl;
//读模式ifstream inf("hcf.txt");if (inf.is_open()) cout << "hcf.txt is open" << endl;string s2;//inf >> s2;getline(inf,s2); //注意读取时字符串有空格cout << s2 << endl;
//读写模式fstream fs4("hcf.txt");//默认为读写模式,也可以显示指定vector<int> iv = { 1, 12, 3, 4, 5, 6 };/*for (auto x : iv)   fs4 << x << " ";fs4 << '\0';*/string s3 = "learning by doing\n";fs4 << s3<<endl;string s4;getline(fs4, s4);cout << s3 << endl;//copy(begin(iv), end(iv), ostream_iterator<int>(fs4, " "));

如果文件中已有内容,读写时需要注意打开模式如果你不具体指明文件的打开模式,fstream类会使用缺省模式。例如,ifstream在缺省情况下会以读的模式打开一个文件,并把文件指针定在文件的起始处。












阅读全文
0 0
原创粉丝点击