在准确显示代码之前,让我详细解释一下这个问题。 我需要创建2个dat文件,其中包含一些关于酒店的数据。其中一个文件包含以下信息:酒店所在省份的名称(16个字符串),酒店类别(int),酒店代码(int),酒店名称(30个字符串),金额房间(int)和当前预订房间的数量(int)。第二个dat文件包含从列表中删除的酒店代码。测试的最后一部分是创建一个包含剩余酒店的所有信息的文件。从理论上讲,我已经拥有了2个第一个dat文件的信息,我只是写了一些简单的东西。值得一提的是,我必须使用dev c ++ 4.9.9.2:
#include <iostream>
#include <cmath>
#include <fstream>
#include <string.h>
#include <cstdio>
using namespace std;
struct rhot
{
char provincia[16];
int categoria;
int chot;
char nombrehotel[30];
int canthabitaciones;
int habitreservadas;
};
int main()
{
rhot hot1 =
{
"Còrdoba",
4,
1,
"La pachamama",
100,
49
};
rhot hot2 =
{
"Salta",
3,
2,
"Puntoblanco",
60,
13
};
rhot hot3 =
{
"Catamarca",
4,
3,
"Jaguar Resort",
250,
197
};
rhot hot4 =
{
"Chubut",
6,
4,
"Llao Llao",
300,
299
};
rhot hot5 =
{
"La pampa",
2,
5,
"Gaunchito",
40,
20
};
rhot hot6 =
{
"Mendoza",
3,
6,
"Queseyo",
60,
13
};
FILE* f1;
f1 = fopen("Arhot.dat", "w");
fwrite(&hot1,sizeof(hot1),1,f1);
fwrite(&hot2,sizeof(hot2),1,f1);
fwrite(&hot3,sizeof(hot3),1,f1);
fwrite(&hot4,sizeof(hot4),1,f1);
fwrite(&hot5,sizeof(hot5),1,f1);
fwrite(&hot6,sizeof(hot6),1,f1);
fclose(f1);
system("PAUSE");
return EXIT_SUCCESS;
}
第二个:
#include <iostream>
#include <cmath>
#include <fstream>
#include <string.h>
#include <cstdio>
using namespace std;
struct Rbaja
{
int Cbajas;
};
int main()
{
Rbaja Baja1 =
{
1
};
Rbaja Baja2 =
{
5
};
FILE* f1;
f1 = fopen("Arbaj.dat", "w");
fwrite(&Baja1,sizeof(Baja1),1,f1);
fwrite(&Baja2,sizeof(Baja2),1,f1);
fclose(f1);
system("PAUSE");
return EXIT_SUCCESS;
}
(我还想提一下,我不知道我真正需要哪些库,我尝试删除它们中的每一个并运行程序,即使它没有库也不会给我任何错误,所以只是因为我不知道该怎么办我把他们全部留在那里)
现在我正努力做到这一点。我需要阅读上面创建的2个文件,并尝试根据我在开始时所说的创建一个。但是我几乎没有编写一个fread函数,每当我编译并运行它时它崩溃
#include <iostream>
#include <cmath>
#include <fstream>
#include <string.h>
#include <cstdio>
#include <cstdlib>
using namespace std;
FILE* fileArhot;
FILE* fileArbaj;
FILE* fileAract;
struct rhot
{
char provincia[16];
int catergoria;
int chot;
char nombrehotel[30];
int cantahibaticones;
int habitreservadas;
};
struct rbaja
{
int Cbajas;
};
struct rhotact
{
char provincia[16];
int catergoria;
int chot;
char nombrehotel[30];
int cantahibaticones;
int habitreservadas;
};
int main()
{
fileArhot =fopen("Arhot.dat","r");
fileArbaj =fopen("Arbaj.dat","r");
fileAract =fopen("Aract.dat","w");
fread(&fileArhot,sizeof(rhot),1,fileArhot);
fread(&fileArbaj,sizeof(rbaja),1,fileArbaj);
fclose(fileArhot);
fclose(fileArbaj);
fclose(fileAract);
system("PAUSE");
return EXIT_SUCCESS;
}
每当我尝试运行此程序时,程序崩溃。我认为它是因为它做了无限循环或其他什么,但我不知道。我包含了2个dat文件的创建代码,因为我可能错误地创建了它们。
不管怎样,我想要一些帮助:D (也很抱歉,如果文字是西班牙语,我来自阿根廷,我需要用西班牙语做代码。)
答案 0 :(得分:2)
您将错误的参数传递给fread
;
fread(&fileArhot,sizeof(rhot),1,fileArhot);
覆盖fileArhot
,未定义。
您也忘记声明要读入的变量。
应该是
rhot an_rhot; // or whatever you want to name it
fread(&an_rhot, sizeof(rhot), 1, fileArhot);
或稍微安全
fread(&an_rhot, sizeof(an_rhot), 1, fileArhot);
和其他阅读相似。
您还应添加一些检查,以验证您是否已成功打开,阅读和写入文件。
我建议您考虑使用C ++ I / O而不是C库,因为它更安全。