注册 登录
编程论坛 C++教室

如何捕捉打开不存在的文件产生的异常

circlesky 发布于 2010-06-11 14:34, 890 次点击
各位高手,请帮忙解答打开一个不存的文件时,为什么不抛出异常:下面程序要打开“丸子1.txt”文件并将内容显示出来。如果"丸子1.txt"文件存在,可以显示出来。但"丸子1.txt"文件不存在时,为什么不抛出异常并捕捉异常(我要想的结果是输出“文件打开失败!”这句话),而是在当前目录下生成一个空的"丸子1.txt"文件。请帮忙解答,谢谢!下面程序我是在VC++6.0下调试的。

#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
int main(void){
    char str[256];
    ifstream ifs("丸子1.txt");
    try
    {
        if(ifs.fail())
        {
            throw "文件打开失败!\n";
        }
    }
    catch(char* s)
    {
        cout << s;
        exit(1);
    }
    while(!ifs.eof())
    {
        ifs.getline(str,sizeof(str));
        cout << str << endl;
    }
    ifs.close();
    return 0;
}
4 回复
#2
ciweitou1632010-06-11 14:47
程序代码:
   
#include <fstream>
#include <iostream>
using namespace std;

int main(void)
{   
   ifstream inputStream;
   inputStream.open("丸子1.txt");
   if( !inputStream ) {
     cerr << "文件打开失败!" << endl;
     return 0;
   }
   return 0;
}
#3
lijm19892010-06-11 15:35
打开方式不对。
程序代码:
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
int main(void){
    char str[256];
    ifstream ifs("D:\\丸子1.txt" ,ios::in|ios::nocreate);
    try
    {
        if(ifs.fail())
        {
            throw "文件打开失败!\n";
        }
    }
    catch(char* s)
    {
        cout << s;
        exit(1);
    }
    while(!ifs.eof())
    {
        ifs.getline(str,sizeof(str));
        cout << str << endl;
    }
    ifs.close();
    return 0;
}
#4
audioMan862010-06-12 16:17
路过
#5
leoshi2010-06-16 16:58
楼主还是把文件读写的函数及参数好好参考下
1