C++使用流类的构造函数打开文件
发布时间:2023-06-14 13:38:12 所属栏目:语言 来源:
导读:定义流对象时,在构造函数中给出文件名和打开模式也可以打开文件。以 ifstream 类为例,它有如下构造函数:
ifstream::ifstream (const char* szFileName, int mode = ios::in, int);
第一个参数是指向文件名的指
ifstream::ifstream (const char* szFileName, int mode = ios::in, int);
第一个参数是指向文件名的指
定义流对象时,在构造函数中给出文件名和打开模式也可以打开文件。以 ifstream 类为例,它有如下构造函数: ifstream::ifstream (const char* szFileName, int mode = ios::in, int); 第一个参数是指向文件名的指针;第二个参数是打开文件的模式标记,默认值为ios::in; 第三个参数是整型的,也有默认值,一般极少使用。 在定义流对象时打开文件的示例程序如下(用流类的构造函数打开文件): #include <iostream> #include <fstream> using namespace std; int main() { ifstream inFile("c:\\tmp\\test.txt", ios::in); if (inFile) inFile.close(); else cout << "test.txt doesn't exist" << endl; ofstream oFile("test1.txt", ios::out); if (!oFile) cout << "error 1"; else oFile.close(); fstream oFile2("tmp\\test2.txt", ios::out | ios::in); if (!oFile2) cout << "error 2"; else oFile.close(); return 0; } 注意,当不再对打开的文件进行任何操作时,应及时调用 close() 成员方法关闭文件。有关该方法的用法,后续会做详细讲解。 (编辑:汽车网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |