#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main() {
constint MAX = 30;
int length = 0;
//Input:
char buffer[MAX];
char buffer2[MAX];
int number = 10;
int number2 = 20;
//Output:
char r_buffer[MAX];
char r_buffer2[MAX];
int r_number = 0;
int r_number2 = 0;
ofstream file;
file.open("binary.bin", ios_base::out | ios_base::binary);
if (!file.is_open()) {
cout << "Something went wrong while creating the file." << endl;
}
else {
strcpy(buffer, "First input in the file.");
strcpy(buffer2, "Second input in the file.");
file.write((char*)&buffer, sizeof(buffer));
file.write((char*)&number, sizeof(int));
file.write((char*)&buffer2, sizeof(buffer2));
file.write((char*)&number2, sizeof(int));
file.close();
}
ifstream reader;
reader.open("binary.bin", ios_base::in | ios_base::binary | ios_base::app);
if (!reader.is_open()) {
cout << "Something went wrong while openning the file." << endl;
}
else {
int length = 0;
reader.seekg(sizeof(buffer), ios_base::beg);
length = reader.tellg();
reader.read((char*)r_buffer, length);
reader.close();
string sentense = r_buffer;
cout << sentense << endl; //outputs a blank space
}
system("PAUSE");
return 0;
}
I don't get what I am doing wrong. I am sorry if this topic has already been discused but I looked on many forums and never saw any clear response for my problem.
strcpy(data.buffer, "First input in the file.");
strcpy(data2.buffer2, "Second input in the file.");
file.write((char*)&data, sizeof(data));
file.write((char*)&data2, sizeof(data2));
The claim about removing the & is about as useful as alerting programmers to the effects of removing ; at the end of the line.
You're missing the point(er).
r_buffer2 "decays" to a pointer to the first character of the array. Placing the & in front of r_buffer2 takes the address of that pointer resulting in a pointer to a pointer. The extraneous cast masks the error by telling the compiler to ignore the type mismatch. IOW, read is expecting a char pointer, but is being passed a pointer to a pointer. The read is going to read into memory at the wrong place.