fstream - files

closed account (jvqpDjzh)
//Hello guys! Can you help me to improve my code? (not about making it OOP...)
//Are there serious problems in my 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
49
50
51
52
53
54
#include <fstream>
#include <iostream>
using namespace std;

int main(){

    int size = 0;
    char* str = NULL;

    cout << "Enter the size of your string: ";
    cin >> size;
    cin.ignore();//Can you explain me why should I put here cin.ignore()?

    str = new char[size];

    cout << "Enter the string: ";
    cin.getline(str, size);
    //cout << str << endl;
    //
    //
    fstream file("text.dat", ios::out|ios::binary);

    if(file.is_open())
    {
        file.write(str, size);
        file.close();
    }
    //
    //
    file.open("text.dat", ios::in|ios::binary|ios::ate);

    streampos len;

    if( file.is_open() && file.good() && (!file.fail()) && (!file.bad()) )
    {
        len = file.tellg();
        //cout << len << endl;

        str = new char[len];

        file.seekg(0, ios::beg);//

        file.read(str, len);//stores what it reads in the pointer "str"

        cout << str << endl;

        delete [] str;

        file.close();
    }
    else cerr << "Unable to open the file.\n";
    
return 0;
}
Last edited on
Topic archived. No new replies allowed.