如何在 C++ 中使用更改光标输入和输出二进制文件

how to input and out put in a binary file in with changing cursor in c++?

本文关键字:光标 输入 二进制文件 输出 C++      更新时间:2023-10-16

我在写入文件时遇到问题并读回文件。当我在追加模式下打开文件时。当我更改文件的光标时,它只是混合在一起并且不起作用。如何在哈希位置写入文件并使用 Order(1) 使用哈希读回它?顺便说一下,谢谢你的帮助。

struct student{
    int id;
    char name[20];
}st;
int hashing(char word[20])
{
        int hash;
        int sum=0;
        int z;
    sum += (int)word[0];
    sum += (int)word[1];
    z=(sum)%1000;
    hash=z*sizeof(student);
    return hash;
}
void main()
{
fstream op("d://ttest.txt",ios::app | ios::binary);
if(!op)
{
    cout<<endl<<"cant open file :D in write !!!!!!:"<<endl;
    getch();
}
for (int i = 0; i < 3; i++)
{
    cin>>st.id>>st.name;
    op.seekp(hashing(st.name),ios::beg);
    op.write((char *)&st,sizeof(student));
}
op.close();
cout<<endl<<endl<<endl;
fstream op2("d://ttest.txt",ios::in | ios::binary);
if(!op2)
{
    cout<<endl<<"cant open file :D in write !!!!!!:"<<endl;
    getch();
}
char temp[20];
for (int i = 0; i < 3; i++)
{
    st.id=0;
    cin>>temp;
    op2.seekp(hashing(temp),ios::beg);
    op2.read((char *)&st,sizeof(student));
    cout<<st.id<<"  "<<st.name<<endl;
    //op.seekp(hashing(st.name),ios::beg);
}
op2.close();
getch();
}

下面是如何检测数据库文件是否已初始化的示例,如果没有,则执行初始化:

struct student
{
    int id;
    char name[20];
};
int main()
{
    const std::string filename = "database.txt";
    std::fstream fs;
    // try to open the file
    fs.open(filename, std::ios::in|std::ios::out|std::ios::binary);
    if(!fs)
    {
        // Assume it needs initializing - create new file
        std::cout << "Initializing database: " << filename << 'n';
        student s;
        s.id = -1; // empty
        s.name[0] = '';
        fs.clear();
        fs.open(filename, std::ios::app|std::ios::binary);
        if(!fs)
        {
            // can't recover from this
            std::cout << "ERROR: initializing database: " << filename << 'n';
            return 1;
        }
        // write 1000 empty student records
        for(unsigned i = 0; i < 1000; ++i)
            fs.write((char*) &s, sizeof(s));
        fs.close();
        // try again
        fs.open(filename, std::ios::in|std::ios::out|std::ios::binary);
    }
    if(!fs) // still not working?
    {
        // not just an initialization issue, must abort
        std::cout << "ERROR: opening database: " << filename << 'n';
        return 1;
    }
    // Database open and ready for business ...
}