c++读文件-对try-throw-catch的应用

 1 #include<iostream>
 2 #include<fstream>
 3 #include<stdlib.h>
 4 #include<stdio.h>
 5 using namespace std;
 6 int main(int argc, char** argv)
 7 {
 8     ifstream file(argv[1]);    
 9     char line[100] = {0};
10 
11     try
12     {
13         if (file.fail())   //如果提供一个不存在的路径就会出错
14             throw argv[1];
15     }
16     catch (char* s)
17     {
18         cout<<"open file:["<<argv[1]<<"] failed"<<endl;
19         exit(1);
20     }
21 
22     while (!file.eof())
23     {
24         file.getline(line, sizeof(line)/sizeof(char)); //读取文件每一行,直到文件结束
25         cout<<line<<endl;
26     }
27 
28     file.close();  //切记关闭文件啊.
29 
30     return 0;
31 }

 

posted @ 2016-06-05 14:46  哈哈不是嘎嘎  阅读(656)  评论(0编辑  收藏  举报