C++简单的文件I/O(一)

写入到文本文件:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    ofstream outFile;            
    outFile.open("123.txt");        
    outFile<<"123"<<endl;
    outFile.close();    
    return 0;
}

首先声明ofstream对象outFile,将其与文件123.txt关联起来,这样就可以像cout一样使用了,不过这次输出不在屏幕而在文件里。最后再用close()关闭对象。
要是觉得麻烦,可以把前两句合成一句:

ofstream outFile("123.txt");

找到并打开123.txt(当前目录下):

这里写图片描述

读取文本文件:

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main(){
    char line[10];
    ifstream inFile;
    inFile.open("123.txt"); 
    if(!inFile.is_open())               //检查文件是否成功打开
    {
        cout<<"cannot open!"<<endl;
        exit(EXIT_FAILURE);
    }
    inFile>>line;
    //inFile.getline(line, 10);             //方法同上
    cout<<line;
    inFile.close(); 
    return 0;
}

声明ifstream对象inFile,将其与文件123.txt关联起来,这样就可以像cin一样使用了,不过这次是从文件读入进去。

文件模式常量:

附录一份,这个便是打开文件时的openmode,详细地以后再和大家说。

常量 含义
ios_base::in 打开文件时做读操作
ios_base::out 打开文件时做写操作
ios_base::app 在每次写之前找到文件尾
ios_base::ate 打开文件后立即将文件定位在文件尾
ios_base::trunc 打开文件时清空已存在的文件流
ios_base::binary 以二进制模式进行IO操作

猜你喜欢

转载自blog.csdn.net/weixin_41656968/article/details/80914709