C++文件操作

1.ofstream fout("aa"); 写文件操作 写的文件是aa
2.ifstream

写二进制文件
ofstream fout("bb",ios::binary);


#include <iostream>

using namespace std;

int main1(int argc, char *argv[])
{
    char buf[100];
    while(cin.getline(buf,10,'S'))
        cout<<buf<<endl;
    return 0;
}
int main1()
{
    char ch[20];
    cout<<"enter a sentence"<<endl;

    cin>>ch;
    cout<<"The String read with cin is:"<<endl;

    cin.getline(ch,20,'/');
    cout<<"secndpart :"<<ch<<endl;

    cin.getline(ch,20);
    cout<<"third part:"<<ch<<endl;
    return 0;
}



#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
void fun1()
{
    ofstream fout("sylar");
    if(!fout)
    {
        cout<<"failed open"<<endl;
    }
    int a = 10;
    char c = 'S';
    char *s = "hello world";
    fout<<"a = "<<a<<", c = "<<c<<",s = "<<s<<endl;

    fout.close();
}
void fun2()
{
    ifstream fin("sylar");
    if(!fin)
    {
        cout<<"failed open"<<endl;
    }
    char buf[100];
//    while(fin.getline(buf,100))
//    {
//        cout<<buf<<endl;
//    }
    int a;
       char c;

       fin.ignore(4);
       fin>>a;
       cout << a << endl;
       fin.ignore(6);
       fin>>c;
       cout << c << endl;
       fin.ignore(5);
       fin>>buf;
       cout << buf << endl;


       fin.close();
}
class Student
{
public:
    Student(int id = 0,string name = " ")
    {
        this->id = id;
        strcpy(this->name,name.c_str());

    }
    void show()
    {
        cout<<"id = "<<id<<",name = "<<name <<endl;
    }

private:
    int id;
    char name[20];
};
void func3()
{
    ofstream fout("boomer",ios::binary);
    if(!fout)
    {
        cout<<"failed open"<<endl;
        return ;

    }
    Student s1(1,"小明1");
    Student s2(2,"小明2");
    Student s3(3,"小明3");
    Student s4(4,"小明4");
    fout.write((char*)&s1,sizeof(s1));
    fout.write((char*)&s2,sizeof(s2));
    fout.write((char*)&s3,sizeof(s3));
    fout.write((char*)&s4,sizeof(s4));



}
void func4()
{
    ifstream fin("boomer");
    if(!fin)
    {
        cout<<"failed open"<<endl;
        return;
    }
    Student s1;
    for(int i = 0;i<4;i++)
    {
        fin.read((char*)&s1,sizeof(Student));
        s1.show();

    }
    fin.close();
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值