zl程序教程

您现在的位置是:首页 >  后端

当前栏目

笔记:C++文件操作,打开、关闭与读写

C++文件笔记 操作 关闭 打开 读写
2023-09-27 14:19:45 时间

1:文件的打开与关闭

ifs.open(“D:\Workplace\1.txt”,ios::in)

ios::app: 以追加的方式打开文件
ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in: 文件以输入方式打开(文件数据输入到内存)
ios::out: 文件以输出方式打开(内存数据输出到文件)
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc: 如果文件存在,把文件长度设为0
示例:

#include<iostream>
#include<stdio.h>
#include<fstream>//文件读写必须要加入的头文件

using namespace std;

int main()
{
    ifstream ifs;
    ifs.open("D:\\Workplace\\1.txt",ios::in);
    // 每个“\\”的第一个\是转义字符,第二个翻译为正常\
    //ios::in是打开供读取的文件
    if(!ifs)
        cout<<"no"<<endl;
    if(ifs)
        cout<<"yes"<<endl;

    ifs.close();
    return 0;
}

2:文件的读取

#include<iostream>
#include<stdio.h>
#include<fstream>

using namespace std;

int main()
{
    ifstream ifs;
    char* buf;

    ifs.open("D:\\Workplace\\1.txt",ios::in);
    while(!ifs.eof())
    {
        ifs.getline(buf,256,'\n');//按行读,将读出来的一行暂时放到buf中
        cout<<buf<<endl;
    }
    return 0;
}

3:文件的写入
示例:将26个字母,每五个一行写入文件中

#include<iostream>
#include<stdio.h>
#include<fstream>

using namespace std;

int main()
{
    ofstream ofs;
    ofs.open("D:\\Workplace\\1.txt",ios::out);
     //ios::out是打开或创建一个一个供写入的文件,
    char ch='a';
    if(ofs)
    {
        for(int i=0;i<26;i++)
        {
            ofs<<ch;
            if(i>0&&i%5==0)//每五个字母写入一个换行符
                ofs<<endl;
            ch++;
        }
    }
    return 0;
}