Reading and writing classes with pointers to binary files in c++ - pointers

I've been trying to write some data to a binary file in c++ using fstream and most examples go like this:
#include <fstream>
class Person{
public:
int age;
char name[50];
}
int main(){
Person joe;
joe.age = 50;
strncpy(joe.name, "Joe Jones");
fstream file("filename.dat", ios_base::binary);
file.write((char*)joe, sizeof(joe));
file.close();
}
This works just as expected but the problem arises when I try to write a more complex structure, mainly one with pointers instead of the actual data.
class Person{
public:
int age;
int *friendsAges;
Person(int friends){
friendsAges = new int[friends];
}
}
When I write the data like before
Person joe(10);
/* Initialize rest of joe */
file.write((char*)joe, sizeof(joe));
the resulting file has 8 bytes of data, 4 for the age and 4 for the address of the friendsAges array or so it seems.
How could I go about writing the actual data that is stored in the array? I have also had this problem when my classes have other classes as members such as a Person having a Car or something like that.

For starters, add a method to your class that will perform the file I/O then you can just call it like so:
Person joe();
Person sally();
fstream file("filename.dat", ios_base::out | ios_base::binary);
joe.serialize(file, true);//writes itself to the file being passed in
sally.serialize(file, true); //write another class to file after joe
file.close();
Then later you could read that same file to populate the class instance:
fstream file("filename.dat", ios_base::in | ios_base::binary);
joe.serialize(file, false); //reads from file and fills in info
sally.serialize(file, false); //reads from file too
file.close();
The method in the class would look something like this:
Person::serialize(fstream &fs, bool bWrite)
{
int ages_length;
if (bWrite) {
fs.write(&age, sizeof(age));
ages_length = ...; //you need to know how long the friendsAges array is
fs.write(&ages_length, sizeof(ages_length)); //write the length to file
fs.write(&friendsAges[0], sizeof(int)*ages_length); //write the variable-sized array to file
fs.write(&name[0], sizeof(char)*50); //write a string of length 50 to file
}
else {
fs.read(&age, sizeof(age));
fs.read(&ages_length, sizeof(ages_length)); //read length of array from file
//TODO: you will need to malloc some space for *friendsAges here
fs.read(&friendsAges[0], sizeof(int)*ages_length); //read-in the variable length array
fs.read(&name[0], sizeof(char)*50); //this only works if string length is always fixed at 50
}
}

Related

After I declare an object from a class, and try to set a variable to that object inly, why does it say that it does not declare a type?

I am writing code for a school project that will be used for a Chromebook charging station with security. The problem I am having now is when I am detecting if a Chromebook is actually in the slot after the user has been assigned one, I am using a rocker switch to simulate this but when I am declaring the pin to the rocker, the arduino verfier comes up with that
"'slot1' does not name a type".
Code is below:
//class
class Chromebook_slot {
public:
String Name = "";
String RFID_tag = "";
int rocker = 0;
boolean chromebook_in = false;
//class function to check if chromebook is in.
//if not, redirect already to reassigning so chromebook slot is entered as open and free.
void set_if_in()
{
int momen_1_state = digitalRead(momen_1);
int momen_2_state = digitalRead(momen_2);
// the button has been pushed down and the previous process has been completed
// eg. servos would have been reset if there was a previous user
if (momen_1_state == HIGH || momen_2_state == HIGH)
{
chromebook_in = digitalRead(this->rocker);
if (chromebook_in == 0)
{
re_assigning();
}
else
{
return;
}
}
}
};
//this is now outside the class..
//class declarations
Chromebook_slot slot1;
Chromebook_slot slot2;
//variables for rocker switches which will act for detecting chromebooks.
// in my final version, this will replaced by a photoresistor and laser.
slot1.rocker = 3;
slot2.rocker = 2;
Where the function re_assigning() is a separate function declared further in the code and just resets the slot as open for future use.
slot1.rocker = 3;
slot2.rocker = 2;
These are statements that cannot be at the top level of a C++ (or .ino) file. They need to be inside of a function. What's happening is the compiler is looking looking at the slot1 identifier through the lens of potential valid constructions. It sees an identifier, and about the only thing that could legally exist at this point in the code that starts with an identifier like that is some declaration, e.g. int a = 7;, or more abstractly some_type some_more_stuff. So it expects slot1 to be a type, which it isn't, hence the message.
If you want an assignment like those to happen early on in an Arduino program, the simplest thing you could do is put them in setup():
void setup() {
slot1.rocker = 3;
slot2.rocker = 2;
// ...
}
Or, you'd make these part of the Chromebook_slot's constructor, such that they could be given in slot1 and slot2's declaration:
class Chromebook_slot {
public:
Chromebook_slot(int rocker_init_value) {
rocker = rocker_init_value;
}
// ...
Or in a maybe less familiar but more proper form, using the constructor's initialization list:
class Chromebook_slot {
public:
Chromebook_slot(int rocker_init_value)
: rocker(rocker_init_value) {}
// ...
Once you have a constructor for Chromebook_slot, your variables can become:
Chromebook_slot slot1(3);
Chromebook_slot slot2(2);

Turbo C++ File Handling: Stuck in input loop

I am making a program in turbo C++ to create student records and modify/delete them in a binary file on user's command.
The main class that is needed to know is the student class:
class student
{
private:
int roll_no;
char name[50];
academic ac;
co_curricular cc;
void calculate();
public:
int get_data(int);
void show_data();
void show_tabular();
int ret_roll_no();
};
There is some problem with the get_data() function, specially in the part where the roll number is assigned. The logic to assign the roll number is:
student temp;
fstream fp;
roll_no = random(9000) + 1000;
//Checking if roll number is unique
fp.open("STUDENT.DAT", ios::in);
while(!fp.eof())
{
fp.read((char*)&temp, sizeof(temp));
if(roll_no == temp.ret_roll_no())
roll_no = random(9000) + 1000; //Set roll number to another random value
}
fp.close();
Binary file STUDENT.DAT already exists, but the code doesn't go after the loop. It is somehow stuck.
Please help

Qt -how to get variable value from another function in same file

New to Qt. Still learning it. I have clone.ui, clone.h and clone.cpp. clone ui has 2 buttons.
Browse button-> to Selection a destination path
Add button -> Clone(copy) a file
Clone.h
QString destination_path;
QFileDialog *fdialog;
Clone.cpp has
QFileInfo finfo; // Declare outside function to increase scope
QString destination_name;
void Clone:: on_pushButton__Browse_clicked()
{
/*get the destination path in QString using QFileDialog
Got destination_path */
QString destinatino_path = QFileDialog::getExistingDirectory(....);
QFile finfo(destination_path);
// QFileDialog finfo(destionation_path)
}`
In the same file Clone.cpp
void Clone:: on_btn_Add_clicked()
{
// how to get the same destination_path value here...
//using QFile or some other way?
}
I struck here, Am i missing anything? Any thoughts/suggestion highly useful.
You've create a class (Clone) which has a data member QString destination_path.
Since it is a member variable it has class scope (as in you can access the same variable in any Clone:: member function for the same Clone object).
The problem is that you've hidden it by declaring another QString destination_path in Clone::on_pushButton__Browse_clicked().
void Clone::on_pushButton__Browse_clicked()
{
...
// this *hides* the class member with the same name
QString destination_path = QFileDialog::getExistingDirectory(....);
...
}
The solution is to remove QString from the beginning of the line, which means you are now assigning to the class object's data member.
void Clone::on_pushButton__Browse_clicked()
{
...
// now you're assigning to your object's data member
destination_path = QFileDialog::getExistingDirectory(....);
...
}
Later, in Clone::on_btn_Add_clicked() you can access destination_path, and it will have the value assigned to it in Clone::on_pushButton__Browse_clicked

Alphabet Encryption

Right now I cant even compile this program. Im trying to write a program that takes a inputted string and then encrypts the letters by swapping them out with another letter predetermined in a array and then shows you again the original text. any help would be appreciated.
import java.util.Scanner;
public class Array {
private char [] alphabet = new char [25];
private char [] crypt = new char [25];
String oldMessage;
public Array()
{ char[] alphabet = "abcdefghijklmnoptqrstuvwxyz".toCharArray();
char[] crypt = "qwertyuiopasdfghjklzxcvbnm|".toCharArray();
}
public static void run(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a message that you would like to encrypt\n");
oldMessage = scan.nextLine();
String newMessage = "";
for (int i=0; i<oldMessage.length(); ++i) {
int index = alphabet.indexOf(old.charAt(i));
if (index == -1)
newMessage +="?";
else
newMessage += crypt.charAt(index);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {Array myApplication = new Array(); myApplication.run();}
First off, when encountering errors, it's always best to include the error in your question--often it will point you right to the source of the error. What does your compiler say when the build fails?
Next, I'm on my phone right now and can't verify that I've found all the problems, but remember that strings in Java are immutable, meaning that they can't be changed after creation. This means that you can't append to them in the way you're doing. Try using the StringBuilder class to accomplish what you're looking for here, or filling a new array as you go and converting to String at the end.
Also, it looks like you're missing two end braces (the for loop and the run method).
From static method run() you are referring to non-static variables like alphabet, crypt, oldMessage.
This is first that comes into mind

Save (already-existing) QSetting into an INI file

I want to save an alredy-existing QSettings object into some INI file for backup.
The QSettings comes from the application's global settings, ie. it can be registry, ini file, etc.
In case it helps, my context is:
class Params
{
// All params as data members
// ...
void loadGlobal ()
{
Qettings s; // Global parameters, paths set by application
// Fill data members: s.value (...);
}
};
class Algo
{
Result run (Params p)
{
Result r = F(p);
return r;
}
};
int main (...)
{
Params p;
p.loadGlobal ();
Algo a;
Result r = a.run (p);
// At this point, save Result and Params into a specific directory
// Is there a way to do:
p.saveToIni ("myparams.ini"); // <-- WRONG
}
A solution would be to add a saveTo (QSetting & s) method into the Params class:
class Params
{
void saveTo (QSettings & s)
{
s.setValue (...);
}
};
int main (...)
{
Params p;
p.loadGlobal ();
QSettings bak ("myparams.ini", ...);
p.saveTo (bak);
}
But I am looking for a solution without modifying the Params class.
Well, no, QT Doesn't really support this directly. I think your best bet is writing a helper class...something like:
void copySettings( QSettings &dst, QSettings &src )
{
QStringList keys = src.allKeys();
for( QStringList::iterator i = keys.begin(); i != keys.end(); i++ )
{
dst.setValue( *i, src.value( *i ) );
}
}
I think there are 2 issues:
QSettings does not have a copy constructor or assignment operator (that I know of), so you'll probably have to write your own copy using allKeys().
You can't save QSettings to an arbitrary file, but what you can do is set the path used for a specific format and scope using the static method QSettings::setPath(). Note that you need to do that before your backup QSettings object is created (and you would use format IniFormat).
If you're OK not having complete control over the resulting path, this should be sufficient. If not, you could still do the above, then get the file name using fileName() and use a system call to copy/move the file to the desired final location.

Resources