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

本文介绍了一个使用C++进行文件读取的基本示例,包括异常处理和逐行读取的方法。通过命令行参数接收文件路径,并确保了文件打开成功后才进行后续操作。
 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 }

 

转载于:https://www.cnblogs.com/silentNight/p/5560785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值