C++读写文件

一. 基础知识

  1. 读写文件的头文件:#include
  2. 打开方式:
    ios :: in , 读文件打开;
    ios :: out , 写文件打开(会清空原文件中的所有数据);
    ios :: ate , 从文件尾打开;
    ios :: app , 追加方式打开,在原文件内容后写入新的内容;
    ios :: trunc , 在读写前,先将文件长度截断为0;
    ios :: binary , 以二进制形式打开文件;

二. 写文件
包含头文件 ---> 创建流对象, ofstream ofs; ---> 指定路径和打开方式, ofs.open(路径, 打开方式); ---> 写内容, ofs << "写数据" << endl; --->关闭文件, ofs.close();

代码:

void Write()
{
    ofstream ofs;             //创建流对象
    ofs.open("phone.txt", ios::app);           //指定路径和打开方式
    ofs << "Name " << " Sex "  <<  " Age "  << " Phone "  << "Address" << endl ;        //写数据
}
    ofs.close();        //关闭文件
}

三 .读文件
包含头文件 ---> 创建流对象,ifstream ifs; ---> 指定路径和打开方式,ifs.open(路径, 打开方式); ---> 读内容 ---> 关闭文件

代码:

void Read( )
{
    char buffer[256];
    ifstream ifs;
    ifs.open("phone.txt", ios::in);
    while(!ifs.eof())
    {
        ifs.getline(buffer, 100);
        cout << buffer << endl;
    }
    ifs.close();
}

四. 清空文件数据
代码:

#include 
#include            //C++读写文件的头文件
#include 
using namespace std; 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
 
int main(int argc, char** argv) {
    //清空文件中的数据
    ofstream ofs;
    ofs.open("phone.txt", ios::out);
    ofs.close();
    printf("success"); 
    return 0;
}

五. 删除文本文件【remove()函数】
代码:

#include 
#include            //C++读写文件的头文件
#include 

using namespace std; 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
    char *path = "C:/Users/25165/Desktop/project/读写文件/phone.txt";
    if(remove(path) == 0)
        cout << "删除成功" <

补充:eof()函数问题:
eof()用来检测是否到达文件尾,如果到达文件尾返回非0值,否则返回0。
如下代码:

#include 
#include            //C++读写文件的头文件
#include 

using namespace std; 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
    char buffer[256];
    int count = 0;

    ifstream ifs;
    ifs.open("phone.txt", ios::in);
    
    if(!ifs.is_open())
    {
        cout << "文件打开失败!" << endl;
        return 0;   
    } 
    while(!ifs.eof())        //判断文是否到达文件末尾,如果到达文件尾返回非0值 
    {

        ifs.getline(buffer, 100);
        cout << buffer << endl;
        count++;
    }

    ifs.close();

    printf("%d\n", count);
    return 0;
}

运行结果如图:

运行结果.png

Q:文本中明明只有三行数据,为什么while循环会进行四次?
解:我们用其他编辑器打开文本显示
phone.png

可以看到该文本文件有四行,最后一行没有数据。
解决办法:
我们可以加一个读到的数据不为空的判断if(strlen(buffer) != 0),再进行后续处理。

你可能感兴趣的:(C++读写文件)