提问者:小点点

我似乎不明白为什么我的读/写文件功能不能工作


我一直在做我的项目,我需要做的最后一件事就是在程序启动时保存到文件并开始从文件中读取结构数组,但是我不明白为什么代码没有加载文件的信息。我知道它确实保存了一些东西,因为我可以打开。dat文件并在文本编辑器中读取它。我为糟糕的风格道歉,但我还是新来的。这只是代码中那个函数的示例:

#include <iostream>
#include <string>
#include<fstream>

using namespace std;

struct property {
    int num;
    char nBrok[50];
    char type[10];
    string adress;
    char outlook[20];
    double price;
    double size;
    int nRooms;
    int floor;
    int status;
};
fstream fp;

void fileWrite(property bDanni[], int n) {
    fp.open("dbase.dat", ios::binary | ios::out);
    if (!fp) {
        cout << "\n Error in file \n"; exit(1);
    }
    fp.write((char*)bDanni, sizeof(property) *n);
    fp.close();
}

int fileRead(property bDanni[]) {
    long pos; int n = 0, i; property b;
    fp.open("dbase.dat", ios::binary | ios::in);
    if (!fp) {
        cout << "\n file does not exist\n"; return n;
    }
    fp.seekg(0l, ios::end);
    pos = fp.tellg();
    fp.close();
    n = pos / (sizeof(property));
    fp.open("dbase.dat", ios::binary | ios::in);
    if (!fp) {
        cout << "\n Error in file \n"; exit(1);
    }
    for (i = 0; i < n; i++) {
        fp.read((char*)&b, sizeof(property));
        bDanni[i] = b;
    }
    fp.close();
    return n;
}
int main() {
    property bDanni[100];
    char answer;
    int total = 0;
    cout << "Do you wat to read from the save file?(y/n): ";
    cin >> answer;
    if (answer == 'y') {
      int total = fileRead(bDanni);
    }
}

共1个答案

匿名用户

问题是C++std::string比char数组复杂得多。该实现不是由标准强制要求的,但在常见的实现中,string元素包含指向字符数组的指针。这意味着您的代码只在文件中存储一个指针值,而不是字符串。

在C++习惯用法中,std::string类型被认为是不可复制的。fread-fwrite方法只能用于可复制的类型。

这意味着您必须使用序列化将std::string的原始字节表示形式替换为表示对象有用内容的字节序列,您可以在读取时使用这些字节来构造回对象。并不是很复杂,但不仅仅是fwrite