Binary files...again. Loading for a game.

When I try to open a binary file that doesn't exist does it create one? If not, how can I make it?
Last edited on
Like this:

1
2
3
4
#include <cstdio>
FILE *fp;
fp  = fopen("test.txt", "wb");
fclose(fp);
I don't have a programming environment infront of me, but as far as I can remember, opening a file that does not exist returns an error. Assuming you are using fstream, you can do this to create a file:
1
2
ofstream file("C:/file.txt");
file.close();

That will create a file in C: root, called file.txt. You can then use it as normal. You may want to read: http://cplusplus.com/doc/tutorial/files/
Last edited on
Thanks. I found out it auto-creates one if you don't have one though. The game I'm working, and it can save, but it won't load. Any idea why? This is only my second game/program, and I've only been teaching myself for a week or so, so it may seem a bit ridiculous because I'm not the best coder yet.

main.cpp: http://pastebin.com/X2ibBrQu
Imp.cpp: http://pastebin.com/N3nVC2jk
Player.h: http://pastebin.com/wMN1Qx6r
Imp.h: http://pastebin.com/WLxbLDxV


Player.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "Player.h"
#include <iostream>
#include <fstream>
using namespace std;

Player::Player()
{

}
void Player::IncrStat(int s, int d, int a, int h, int e, int g, int l){

    Strg += s;
    Def += d;
    Agil += a;
    Health += h;
    Exp += e;
    Gold += g;
    Lvl += l;

}

void Player::DecrStat(int s, int d, int a, int h, int e, int g, int l){

    Strg -= s;
    Def -= d;
    Agil -= a;
    Health -= h;
    Exp -= e;
    Gold += g;
    Lvl += l;

}

void Player::save(){

    ofstream S;
    S.open("SAVE.bin", ios::binary | ios::out);
    S.write((char*)(&Strg), sizeof(Strg));
    S.write((char*)(&Def), sizeof(Def));
    S.write((char*)(&Agil), sizeof(Agil));
    S.write((char*)(&Exp), sizeof(Exp));
    S.write((char*)(&Gold), sizeof(Gold));
    S.write((char*)(&Lvl), sizeof(Lvl));
    S.close();
    if (! S){
        cout << "File could not be saved!\n";
    }
}

void Player::load(){

    ifstream S;
    S.open("SAVE.bin", ios::binary | ios::in);
    S.read((char*)(&Strg), sizeof(Strg));
    S.read((char*)(&Def), sizeof(Def));
    S.read((char*)(&Agil), sizeof(Agil));
    S.read((char*)(&Exp), sizeof(Exp));
    S.read((char*)(&Exp), sizeof(Exp));
    S.read((char*)(&Gold), sizeof(Gold));
    S.read((char*)(&Lvl), sizeof(Lvl));
    S.close();
    if (! S){
        cout << "File could not be loaded!\n";
    }
}

void Player::lose_h(int n){
Health -= n;

}
void Player::set_h(){

Health = 50;
}
Last edited on
Topic archived. No new replies allowed.