C++Note文件操作 读文件

读文件步骤:

1.包含头文件

  #include<fstream>

2.创建流对象

  ifstream ifs;

3.打开文件并判断文件是否打开成功

  ifs.open("文件路径",打开方式)

4.读取数据

  四种方式读取

5.关闭文件

  ifs.close();

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 using namespace std;
 5 //文本文件 读文件
 6 void test() 
 7 {
 8     //1.包含头文件 
 9     //2.创建流对象
10     ifstream ifs;
11     //3.打开文件 并且判断是否打开成功
12     ifs.open("test.txt", ios::in);//不限制路径 默认访问项目本地路径
13     if (!ifs.is_open())
14     {
15         cout << "文件打开失败" << endl;
16         return;
17     }
18     //4.读取数据  4中方式
19     //第一种
20     //char buf[1024] = {0};
21     //while (ifs >>buf)
22     //{
23     //    cout << buf << endl;
24     //}
25     //第二种
26     //char buf[1024] = { 0 };
27     //while (ifs.getline(buf, sizeof(buf)))
28     //{
29     //    cout << buf << endl;
30     //}
31     //第三种
32     //string buf;
33     //while (getline(ifs, buf))//头文件 string
34     //{
35     //    cout << buf << endl;
36     //}
37     //第四种:不推荐使用  效率低
38     char c;
39     while ((c = ifs.get()) != EOF)//EOF  end of file 文件尾
40     {
41         cout << c;
42     }
43     //5.关闭文件
44     ifs.close();
45 }
46 int main()
47 {
48     test();
49     system("pause");
50     return 0;
51 }

总结:

  读文件可以利用  ifstream  或者 fstream类

  利用 is_open函数可以判断文件是否打开成功

  close关闭文件

posted on 2023-07-30 12:21  廿陆  阅读(39)  评论(0)    收藏  举报

导航