源程序:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("c:\tmp\test.txt", ios::in); //以读的方式打开文本文件
if (inFile) //打开成功,inFile值为true
{
cout << "成功打开文件:c:\tmp\test.txt
";
inFile.close(); //关闭文件
}
else
cout << "打开文件失败:c:\tmp\test.txt
";
ofstream outFile;
outFile.open("test1.txt", ios::out); //以写方式打开文本文件
if (!outFile) //条件成立,则说明文件打开成功
cout << "error1" << endl;
else
{
cout << "成功打开文件:test1.txt
";
outFile.close();
}
outFile.open("c:\tmp\test2.txt", ios::out | ios::in); //以读写方式打开文本文件
if (outFile) //条件成立,则说明文件打开成功
{
cout << "成功打开文件:tmp\test2.txt" << endl;
outFile.close();
}
else
cout << "error2" << endl;
fstream ioFile;
ioFile.open("..\test3.txt", ios::out | ios::in | ios::trunc); //以读写方式创建文件
if (!ioFile) //条件成立,则说明文件创建出错
cout << "error3" << endl;
else
{
cout << "成功打开文件:..\test3.txt" << endl;
ioFile.close();
}
system("pause");
return 0;
}
运行结果: