ok so i am doing a homework with random access files .
I created a class with all the variables and made the implementation. Now i am trying to create a .dat file and create 50 blank records in it but i cannot seem to get the data written into it at all with the write() function, here is parts of the code:
Code:
//record.h
#include <iostream>
using namespace std;
class record
{
private:
int recordNum;
char toolname[25];
int quantity;
double cost;
public:
void setRecordNumber(int);
int getRecordNumber() const;
void setToolName(string);
string getToolName() const;
void setQuantity(int);
int getQuantity() const;
void setCost(double);
double getCost() const;
};
Code:
//record.cpp
#include <iostream>
#include <cstring>
#include <string.h>
#include "record.h"
using namespace std;
void record::setRecordNumber(int number)
{
recordNum = number;
}
int record::getRecordNumber() const
{
return recordNum;
}
void record::setToolName(string tool)
{
const size_t newsize = 25;
char name[25];
strcpy_s(name, tool.c_str());
toolname[25] = name[25];
}
string record::getToolName() const
{
return toolname;
}
void record::setQuantity(int q)
{
quantity = q;
}
int record::getQuantity() const
{
return quantity;
}
void record::setCost(double price)
{
cost = price;
}
double record::getCost() const
{
return cost;
}
Code:
//function to create and initialize .dat file with 50 blank records
void initializefile()
{
record blank;
blank.setCost(0.0);
blank.setQuantity(0);
blank.setRecordNumber(0);
blank.setToolName(" ");
ofstream create("hardware.dat", ios::out|ios::binary);
if (!create)
{
exit(1);
}
create.write("Record# Tool name Quantity Cost\r\n",sizeof(record) );
for(int x =0 ;x < 50 ; x++)
{
create.seekp((x+1)sizeof(record), ios::beg);
create.write(reinterpret_cast <char*> (&blank) , sizeof(record));
}
when using notepad to view the DAT file, its just garbage and the data is all over the place with weird characters, i want 0 to be in all the fields except toolname where its just blank but i cant seem to get any data written to the file because of the reinterpret_cast as i couted the result of each data before that line and the answer was fine , it wasn't garbled or anything.
I would appreciate some help with this.
thanks in advance.