读文件
读文件与写文件步骤相似,但是读取方式相对于比较多
读文件步骤如下:
- 包含头文件
#include - 创建流对象
ifstream ifs; - 打开文件并判断文件是否打开成功
ifs.open(“文件路径”,打开方式); - 读数据
四种方式读取 - 关闭文件
ifs.close();
```cpp/*
* First Way to read a text file.
*/
void Read1(){
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open()) {
cout << "File Open Failed!" << endl;
}
char buf[1024] = { 0 };
while (ifs >> buf) {
cout << buf << endl;
}
ifs.close();
}
/*
* Second Way to read a text file.
* Use Member function getline.
*/
void Read2(){
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open()) {
cout << "File Open Failed!" << endl;
}
char buf[1024] = { 0 };
while (ifs.getline(buf,sizeof(buf))) {
cout << buf << endl;
}
ifs.close();
}
include
include
include
using namespace std; /*- First Way to read a text file. / void Read1(){ ifstream ifs; ifs.open(“test.txt”, ios::in); if (!ifs.is_open()) { cout << “File Open Failed!” << endl; } char buf[1024] = { 0 }; while (ifs >> buf) { cout << buf << endl; } ifs.close(); } /
- Second Way to read a text file.
- Use Member function getline. / void Read2(){ ifstream ifs; ifs.open(“test.txt”, ios::in); if (!ifs.is_open()) { cout << “File Open Failed!” << endl; } char buf[1024] = { 0 }; while (ifs.getline(buf,sizeof(buf))) { cout << buf << endl; } ifs.close(); } /
- Thired Way to read a text file.
- Use globe function getline. / void Read3() { ifstream ifs; ifs.open(“test.txt”, ios::in); if (!ifs.is_open()) { cout << “File Open Failed!” << endl; } string buf; while (getline(ifs,buf)) { cout << buf << endl; } ifs.close(); } /
- Fouth to use member function get()
*/
void Read4() {
ifstream ifs;
ifs.open(“test.txt”, ios::in);
if (!ifs.is_open()) {
} char c; while ((c = ifs.get())!=EOF) {cout << "File Open Failed!" << endl;
} ifs.close(); } int main() { Read@@@@(); return 0; } ```cout << c;
- 读文件可以利用 ifstream ,或者fstream类
- 利用is_open函数可以判断文件是否打开成功
- close 关闭文件