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;
}
C++文件操作
最新推荐文章于 2024-11-01 13:55:46 发布