gpt4 book ai didi

C++ 读/写二进制模式

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:28:33 25 4
gpt4 key购买 nike

我在学校学习 C++,在我看来这是一门美丽的语言,但我有这个烦人的问题。在教科书中它是用FILE *text写的和 scanfprintf ,我个人不喜欢它;我习惯了cincout或者用 << >>最好用 fstream 说.

所以这是我的问题:

  1. 我必须制作一个以二进制模式写入数据的应用程序(我已经完成了一半但由于某种原因它没有以二进制模式写入)

  2. 在我写下城市 (orasul) 坐标(x 和 y)后,我必须搜索它们并获取这些值。 (这里我尝试使用 string.find )但我必须使用 seekg以“二进制模式”搜索并在结构中分离这些值。

如果你们能以某种方式指导我,因为我在这里很迷路。有没有办法让我得到 sizeof(struct)

#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
#include <limits>

using namespace std;

struct oras {
std::string orasul;
int x;
int y;
} ora;


void functiaPrincipala();
void calculator(float coordonate_x1, float coordonate_y1, float coordonate_x2, float coordonate_y2);
void adaugaOras();
void stergeLocatie();
void repetare();

void main() {
functiaPrincipala();
}

void functiaPrincipala() {
// variabile
int obtiune;
// ofstream fisierOut;
// ifstream fisierIn;


cout << "1) Adauga localitate: " << endl;
cout << "2) Stergerea unei localitati existente: " << endl;
cout << "3) Stergerea tuturor localitatilor existente: " << endl;
cout << "4) Afisarea tuturor localitatilor existente: " << endl;
cout << "5) Calculul distantei a doua localitati: " << endl;
cout << "Introduceti obtiunea: " << endl;
cin >> obtiune;

switch (obtiune) {
case 1:
adaugaOras();
break;
case 2:
stergeLocatie();
break;
case 3:
break;
case 4:
break;
case 5:
break;
}

getch();
}

void calculator(float coordonate_x1, float coordonate_y1, float coordonate_x2, float coordonate_y2) {
float rezultat;


rezultat = sqrt((coordonate_x2 * coordonate_x1) - (coordonate_x2 * coordonate_x1) + (coordonate_y2 * coordonate_y1) - (coordonate_y2 * coordonate_y1));

cout << "Distanta de la orasul 1 la orasul 2 este de: " << rezultat;

}

void adaugaOras() {
int n;
ofstream fisierOutt("textttt.txt", ios::app | ios::binary);

// fisierOutt.open("textttt.txt");
cout << "Cate orase doresti sa introduci: ";
cin >> n;
if (fisierOutt.is_open()) {

for (int i = 0; i < n; i++) {
cout << "Introdu numele orasului: ";
cin >> ora.orasul;
cout << "Introdu coordonatele x: ";
cin >> ora.x;
cout << "Introdu coordonatele y: ";
cin >> ora.y;
fisierOutt << ora.orasul << " " << ora.x << " " << ora.y << endl;
cout << endl << endl;




}

} else {
cout << "Nu am putut deschide fisierul";
}
fisierOutt.close();
cout << endl;
// repetare();
}

void stergeLocatie() {

}

void repetare() {
char obtiune;
cout << "Doriti sa mai adaugati ceva sau sa iesiti?(d/n)";
cin >> obtiune;
if (obtiune == 'd') {
functiaPrincipala();
} else {
exit;
}
}

最佳答案

就像我在评论中所说的那样,您无法真正找到特定的条目,因为所有条目的大小都不同。

可以通过单独的索引文件来解决,其中每个索引条目都包含该条目在真实文件中的位置。这样,当您需要条目 X 时,您首先在索引文件中查找到正确的位置,读取该位置,然后使用它在真实数据文件中查找。

这是多少DBM数据库管理员处理他们的数据。

索引文件中的条目必须是固定大小,例如索引中的每个条目都是 std::ostream::pos_type 类型,并且您使用 write写索引,read阅读它。

关于C++ 读/写二进制模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15459490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com