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

时间:2022-07-23
本文章向大家介绍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;
}