Reading and writing to a Binary file


I've recently decided to learn c++ and things have been going along well, but I've hit a snag in the program I'm trying to write.
I've spent the last three days scouring the internet, reading documentation, reading help forums trying to figure out how to do what I want to do and none if it works. Any time I try to apply it to what I'm trying to do it doesn't work.

The first thing I want to do is set up an array of symbols
variabletype(?) variable [3] {"@","#","~"}
take variable[1] ("@")
and write it to a random access binary file file to a certain position in the file

then later, I want to be able to read that specific position and output it as a const char.



1.
1
2
3
char variable[] = {'@', '#', '~'};//array of charachters
//or
const char* variable[] = {"@","#","~"};//array of strings 
I assume you want the first.

2.arrays start from 0, so, in both cases, variable[1] is #.

3. http://www.cplusplus.com/doc/tutorial/files/ there is a "Binary files" section.
Well it took another hour of random trial and error playing the "guess which variable type wont convert to another character type" game...but... I think i've finally gotten it... Here's the code...

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
using namespace std;

char data2[50];
char buffer='X';
string file_name;
ofstream ofile;
int series=0;
int number;

int main ()
{
    cout << "What would you like to call your file? ";
    cin >> file_name;
    ofile.open(string(file_name+".bin").c_str());
    ofile.close();

    cout<<"\n"<<"How many characters will you enter?\n";
    cin>>number;

    for (int a=0; a<=number; a++)
    {
        data2[a]=getch();
    }

    fstream file (string(file_name+".bin").c_str(), ios::in|ios::out|ios::binary);
    if (file.is_open())
    {
        for (int a=0; a<number; a++)
        {
            file.seekg (a, ios::beg);
            file.write (&data2[a],1);
            if(!file.write (&data2[a],1))
                cout<<"write failed\n";
        }
        for (int a=0; a<number; a++)
        {
            file.seekg (a, ios::beg);
            file.read (&buffer, 1);
            cout<<buffer<<"\n";
        }
        file.close();
    }
    else cout << "Unable to open file";



    return(0);
}


Anything that could be done to optimize or improve that?
Topic archived. No new replies allowed.