如何在 C++ 中使用更改光标输入和输出二进制文件
how to input and out put in a binary file in with changing cursor in c++?
我在写入文件时遇到问题并读回文件。当我在追加模式下打开文件时。当我更改文件的光标时,它只是混合在一起并且不起作用。如何在哈希位置写入文件并使用 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 ...
}
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在Qt C++中更改光标
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 防止触摸输入移动的鼠标光标在窗口上
- QT4.8嵌入.使用QCursor :: SetPos()调整鼠标输入会导致一个抽搐的光标
- 使用 Serial.Read 输入在 Arduino 上设置 LCD 光标
- 如果用户没有输入数据,我如何重新定位光标
- 如何在 C++ 中使用更改光标输入和输出二进制文件