The second parameter lets you pass flags to specify what you want to do. In this case, the flag tells the object to write the data to the file in binary mode.
To read in a string with spaces, use getline.
file.getline(a, '\n');
And if you use std::string instead of a char array:
getline(file, a, '\n');
Writing data in binary alone will not ensure 100% safety is unreadable. You'd have to get into encryption for that.
I think you didn't inderstend me. I want to write data in a text file. Then at some point of my program I want to get this data. But I want the text file to show correct values.
Here is example:
Let's say that I have structure Data that has two cmponents - number and name.
I want to insert data in the text file. Let's say I have this:
1 2 3
Data d;
cin >> d.num;
cin.getline(d.name, 100);
How to insert it in the text file so if my input is:
1 Steve Round
and the output in the text file to be:
1 Steve Round
(I know I can just use file << d.num << d.name but maybe this is not right).
And at some point I want to get this data. I do this:
1 2
Data New;
Data.read((char*)&New, sizeof(Data));
But this method is not working.
If I try just: file << New.num << New.name;
I get only the first name.
Can you give me a sample code how to write the info in a readable text file and then extract it?
There is no way to know the length of the string unless you have it explicitly marked in the file somehow.
You can separate all your data by newlines, and read the name with getline(), as suggested to you. (You'll need to be careful to handle other newlines after using >> too.)
You can output another number in front of the string to tell you how many characters to read into the string.
You can surround the string with double-quotes (or some other character or characters), and use getline() to find the second double quote.
Pick one. Each one has some tricky issues to deal with. If you need help then post back.
You know, I missed one. Your name field is 30 characters long, meaning that you cannot have a name longer than 29 characters. Why not just write and read 29 characters?
Yeah, I also think that this is the best way to do it and I will use it in my program. I'm just curious how can I do it if they are on same line (If there is a way). :)