我的C++之旅—06
(原创)
很基础的文件和二进制文件的读写问题。
功能:基础的文件的读写
代码如下:
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
using namespace std;
class Person {
public:
string name;
int age;
}p;
void test01write() {
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "真牛比" << endl;
ofs.close();
}
void test02read() {
ifstream ifs;
ifs.open("test.txt", ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
}
//读取数据方法1
char buf[1024] = { 0 };
while (ifs >> buf) {
cout << buf << endl;
}
//读取数据方法2
char bf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf))) {
cout << bf << endl;
}
//读取数据方法3
string bg;
while (getline(ifs, bg)) {
cout << bg << endl;
}
//读取数据方法4
char c;
while ((c = ifs.get()) != EOF) {
cout << c;
}
ifs.close();
}
void test03write() {
ofstream ofss;
ofss.open("person.txt", ios::out | ios::binary);
p = { "zhangsan",18 };
ofss.write((const char *)&p,sizeof(Person));
ofss.close();
}
void test04read() {
ifstream ifss;
ifss.open("person.txt", ios::in | ios::binary);
ifss.read((char*)&p, sizeof(Person));
cout << p.name << p.age << endl;
ifss.close();
}
int main() {
int i, n, m;
test01write();
test02read();
test03write();
test04read();
system("pause");
return 0;
}