c++文件操作

include<iostream>
#include<fstream>
using namespace std;
#include<string>
void test01()
{
    string l;
    ofstream a;
    a.open("test.txt", ios::out);
    /*getline(cin, l);*/ //可以正常写入空格
    a << "你好!! !" << endl;
    a.close();
}

void test02()
{
    string l;
    ifstream b;
    char arr[100];
    b.open("test.txt", ios::in);

    //1
    //if (!b.is_open())
    //{
    //    return;
    //}
    //else {
    //    b >> arr; //不可以正常输出空格
    //}
    //cout << arr << endl;

    //2
    //if (!b.is_open())
    //{
    //    return;
    //}
    //else {
    //    while (getline(b, l))
    //    {
    //        cout << l << endl;
    //    }
    //}

    //3
    //if (!b.is_open())
    //{
    //    return;
    //}
    //else {
    //    while (b.getline(arr, sizeof(arr)))
    //    {
    //        cout << arr;
    //    }
    //}
    b.close();
}



//int main()
//{
//    test01();
//    test02();
//    return 0;
//}

二进制形式读写

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

class Person {
public:
    int age;
    char* name;
    Person(int age_, const char* name_) {
        age = age_;
        name = new char[strlen(name_) + 1];
        strcpy(name, name_);
    }
    Person(){}
    ~Person()
    {
        delete[] name;
    }
};

void test()
{
    //二进制写
    //Person p(18, "王凌霄");
    //ofstream a;
    //cout << p.name << endl;
    //a.open("test.txt", ios::out | ios::binary);
    //a.write((const char*)&p, sizeof(p));

    //二进制读
    //Person p;
    //ifstream a;
    //a.open("test.txt", ios::in | ios::binary);
    //a.read((char*)&p, sizeof(Person));
    //cout << p.age << endl << p.name << endl;
    
}

int main()
{
    test();
    return 0;
}

 

posted @ 2023-04-16 16:44  aallofitisst  阅读(9)  评论(0)    收藏  举报