c++文件操作之文本文件-读文件

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void test() {
    ifstream ifs;
    //如若不指定路径,则在该项目同级下生成
    ifs.open("test.txt", ios::in);
    if (!ifs.is_open()) {
        return;
    }
    //读文件
    //第一种
    char buf[1024] = { 0 };
    while (ifs >> buf) {
        cout << buf << endl;
    }
    //第二种
    char buf[1024] = { 0 };
    while (ifs.getline(buf, sizeof(buf))) {
        cout << buf << endl;
    }
    //第三种
    string buf;
    while(getline(ifs,buf)) {
        cout << buf << endl;
    }
    //第四种
    char c;
    while ((c = ifs.get()) != EOF) {
        //这里没有endl;
        cout << c;
    }
    ifs.close();
}
int main() {
    test();
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12103028.html