How to fwrite and fread for Vector

Hello,
I made codes in c++, for encryption and decryption. first code creates an output in vector and then write it in a file by using fwrite, and the second reads that output from the first by using fread. Here is the snippet of my codes :

1st 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
 .....
string a;
vector<long long int> c;

cout << "message to be encrypted = ";
cin >> a;   
cout << endl;

cout << "Encrypted message : ";
for (i=0;i<a.size();i++) 
{
    x=(int)a.at(i);
    cout << x << " ";
    c.push_back(powerMod(x,e,n));
}

for (i=0;i<c.size();i++) 
{
    //cout << char(c.at(i));
}
cout << endl;

//Write ciphertext c to a file
FILE * pWrite;
pWrite = fopen ("ciphertext", "w");
fwrite (&c , sizeof(c), 1, pWrite);
fclose (pWrite);


The output is :
1
2
message to be encrypted = test
Encrypted message : 116 101 115 116 


and then my 2nd code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
....
//Read Ciphertext from ciphertext
FILE * pRead2;
pRead2 = fopen ("ciphertext", "r");
fread (&c , sizeof(c), 1, pRead2);
//cout << "ciphertext is " << c << endl;

// Decryption
cout << "Decrypted message : ";
for (i=0;i<c.size();i++) 
{
    cout << powerMod(c.at(i),d,n) << " " ;
}
cout << endl;


The result is
 
Segmentation Fault(Core Dumped)


I appreciate any help, since I don't know where is the problem, in the fwrite or in the fread. I've googled, and found out that the logic to write vector to a file is to get all elements first then write it, and the logic to read is to read all elements and push it back to the vector, is this logic correct?
If it is, how to interpret this logic in c++?
Thank you.
I've googled, and found out that the logic to write vector to a file is to get all elements first then write it, and the logic to read is to read all elements and push it back to the vector, is this logic correct?

Yes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    //Write ciphertext c to a file
    {
        std::ofstream pWrite("ciphertext");
        for(auto n: c)
            pWrite << n << ' ';
    }

    //Read Ciphertext from ciphertext
    {
        std::ifstream pRead2("ciphertext");
        long long n;
        while(pRead2 >> n)
            c.push_back(n);
    }


(could use other forms of loops or the std::copy() function, but the principle is the same)
Topic archived. No new replies allowed.