首页 > 编程语言 > 详细

C++学习 --- 文件操作

时间:2021-08-24 13:53:26      阅读:22      评论:0      收藏:0      [点我收藏+]

技术分享图片

1、文本文件
1.1、写文件

cout 屏幕输出流对象

技术分享图片

技术分享图片

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//文本文件,写文件
void test01() {
    //1、包含头文件 fstream
    //2、创建输出流文件对象
    ofstream ofs;
    //3、指定打开的方式
    ofs.open("text.txt",ios::out);
    //4、写内容
    ofs << "姓名: 张三" << endl;
    ofs << "性别: 女" << endl;
    ofs << "年龄: 22" << endl;
    //5、关闭文件
    ofs.close();
}
?
int main(){
    test01();
?
    system("pause");
    return 0;
}

 

技术分享图片

1.2、读文件

技术分享图片

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//文本文件,读文件
void test01() {
    //1、包含头文件
    //2、创建输入流文件对象
    ifstream ifs;
?
    //3、打开文件并且判断是否打开成功
    ifs.open("text.txt", ios::in);
    if (!ifs.is_open()) {
        cout << "文件打开失败" << endl;
        return;
    }
    cout << "文件打开成功" << endl;
    //4、读数据
    //第一种
    //char buf[4096] = { 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 ) {//EOF end of file
    //  cout << c;
    //}
?
    //5、关闭文件
    ifs.close();
}
?
int main(){
    test01();
?
    system("pause");
    return 0;
}

 

2、二进制文件

技术分享图片

2.1、写文件

技术分享图片

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//二进制文件,写文件
?
class Person {
public:
    char m_Name[64];   //姓名
    int m_Age;         //年龄
};
?
void test01() {
    //1、包含头文件
    
    //2、创建流对象
    //ofstream ofs;
    ofstream ofs("person.txt", ios::out | ios::binary);
    
    //3、打开文件
    //ofs.open("person.txt", ios::out | ios::binary);
    
    //4、写文件
    Person p = {"张三",22};
    ofs.write( (const char *)&p, sizeof(Person));
    
    //5、关闭文件
    ofs.close();    
}
?
int main(){
    test01();
?
    system("pause");
    return 0;
}

 

2.2、读文件

技术分享图片

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//二进制文件,读文件
?
class Person {
public:
    char m_Name[64];   //姓名
    int m_Age;         //年龄
};
?
void test01() {
    //1、包含头文件
?
    //2、创建流对象
    ifstream ifs;
?
    //3、打开文件,判断文件是否打开成功
    ifs.open("person.txt", ios::in | ios::binary);
    if(!ifs.is_open()) {
        cout << "文件打开失败" << endl;
    }
    cout << "文件打开成功" << endl;
    //4、读文件
    Person p;
    ifs.read((char *)&p,sizeof(Person));
    cout << "姓名: " << p.m_Name << "\t年龄: " << p.m_Age << endl;
    //5、关闭文件
    ifs.close();
}
?
int main() {
    test01();
?
    system("pause");
    return 0;
}

 

 

C++学习 --- 文件操作

原文:https://www.cnblogs.com/d1012181765/p/15179644.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!