Using the read() function

Hey guys this question is a continuation of my Phonebook program.
I read through the articles,and this is what Ive written.

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
  class Phonebook
{
private:
    char fname[20];
    char name[15],num[10];
    fstream io;
public:
    Phonebook(){}
    ~Phonebook(){io.close();}
    void create();
    void getfname();
    void getdata();
    void printdata();
};

void Phonebook::create()
{

}

void Phonebook::getfname()
{
    cout<<"Enter the name of the file"<<endl;
    for(int i=0;fname[i]!='\0';i++)
        cin>>fname[i];
}

void Phonebook::getdata()
{
     Phonebook::getfname();
    io.open(fname,ios::in|ios::binary|ios::app);
    char c='y';
    while(c=='y'||c=='Y')
    {
        cout<<"Enter the name & the number"<<endl;
        cin>>name;
        cin>>num;
        
        cout<<"Do you wanna add more?"<<endl;
        cin>>c;
        if(c=='n'||c=='N')
            break;
    }
}

void Phonebook::printdata()
{
     Phonebook::getfname();
    io.open(fname,ios::out|ios::binary|ios::ate);
    char* memblock;
    streampos size=io.tellg();
    memblock= new char[size];
    io.seekg(ios::beg);
    if(io.is_open())
    {
        io.read(memblock,size);
        io.write(memblock,size);
    }
    else
        cout<<"File doesnt exist!!!"<<endl;
    delete [] memblock;
}


The problem is that I dont know how to use the read() function properly.
You see,in the function getdata(),after taking in the name and number,I dont know how to get the chars to be taken as input into the file using read().

What I mean to say is how to take in the name and num chars to read() and flush it to my file??

Any help is appreciated!!!
Yours friendly newbie,
LadyInRed7.
http://www.cplusplus.com/reference/istream/istream/read/

However that is very likely not what you actually want.

In your case, you can use your file just like you do cin and cout

1
2
3
4
5
6
7
8
9
10
11
fstream file;

file.open("filename",ios::out);//treat file like cout
int ivar = 555;
file << ivar; //puts 555 into the file
file.close();

file.open("filename",ios::in);//now treat file like cin
int ivar2 = 0;
file >> ivar2; //reads 555 from the file into ivar2
file.close();


Topic archived. No new replies allowed.