C++ string类的文件操作

来源:百度知道 编辑:UC知道 时间:2024/06/24 09:26:07
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class A
{
string str;
string strTel;
bool bSex;
public:
A(string str_t) { str = str_t; }
A() { str = ""; }
void Disp() { cout << str << endl; }
};

void main()
{
A b;
ifstream infile("Data.dat", ios::in|ios::binary);
if (!infile)
{
cout << "输入:";
string str_t = "";
cin >> str_t;
A a(str_t);
ofstream outfile("Data.dat", ios::out|ios::binary);
outfile.write((char*)&a,sizeof(a));
outfile.close();
system("cls");
cout << "写入数据:\n\na.str=";
a.Disp();
}
else
{
infile.read((char*)&b,sizeof(b));
infile.close();
cout << "读出数据:\n\nb.str=";
b.Dis

std 中的string 不是基本数据类型, 可以认为是一个类, 其内部成员有字符串的指针,字符串的长度,字符目前分配的空间大小 等
(其实这个问题,也就是char a[10] 和 char* a 区别的问题)

测试sizeof(A) 可以验证出str可以是任意长的数据, 而sizeof(A)是不变的, 证明了str 里包含的是字符串地址, 而不是具体的字符. 你还可以分析用UE 分析Data.dat, 由于sizeof(A)为16, 那么0x00~0x0f是A.str, 其中0x04~0x08 是字符串的指针, 0x08~0x0b字符串的长度, 0x0c~0x0f是 分配的空间大小

那么程序保存了a 这个类, 也就是保存的指向字符串的地址, 程序结束后 字符串空间回收, 第二次运行 这块空间很可能已经被修改了, 因此指向的空间值是未知的, 还可能使程序出错

你可以在A里 加个成员char aa[256]之类的数组,这种方法比较简单,用固定长度来保存,而且写在类的内部, 当然也可以写在外部,并采用可变长的方法节约空间
如:outfile.write(a.str.c_str(), a.str.length());这个就是把真正的字符串位置传进去,并保存了它的长度, 所以有个原则:保存数据到硬盘上,不应该保存指针,而应该保存指针指向的内容

你也可以把这个一系列保存操作封装成函数, 直接传一个string类型 就可以完成保存和读取

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class A
{
string str;
string strTel;
bool bSex;
public:
A(string str_t) { str = str_t; }
A() { str = ""; }
string& getStr()