how do you open a binary file?

when i open text files with the fstream using ofstream or ifstream they work fine if i enter unique names or names already found in the directory/folder...

now when i do binary files i can never open them...

the program compiles and runs correctly, but i just can seem to open a file.

is there a suffix i need to use?
like bin?
hi.bin for binary

or
hi.txt for text
Last edited on
Filenames, extensions included, are no more meaningful than variable names.

Even if the file is binary, opening it as text shouldn't fail. It would only do a newline translation and a few other things.
To open a file as binary: std::ifstream file("filename",std::ios::binary);
whats wrong with my code then? also what importance does binary files have?

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
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include <string>
using namespace std;

int get_int(int default_value);
char name[20];

int main() 
{
string filename;

int n;
int age;
int recsize = sizeof(name) + sizeof(int);

cout << "Enter file name: ";
getline(cin, filename);

fstream fbin;
fbin.open(filename.c_str(), ios::binary | ios::in | ios::out);
if (! fbin)
{
cout << "Could not open file " << filename;
return -1;
}

cout << "Enter file record number: ";
n = get_int(0);

cout << "Enter name: ";
cin.getline(name, 19);
cout << "Enter age: ";
age = get_int(0);


fbin.seekp(n * recsize);
fbin.write(name, 20);
fbin.write(reinterpret_cast<char*>(&age), sizeof(int));
fbin.close();
return 0;
}


int get_int(int default_value) 
{
char s[81];

cin.getline(s, 80);
if (strlen(s) == 0)
return default_value;
return atoi(s);
}
Topic archived. No new replies allowed.