Reading and writing binary file c++

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

31 Replies - 2419 Views - Last Post: 21 March 2010 - 09:13 PM Rate Topic: -----

#1 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Reading and writing binary file c++

Posted 18 March 2010 - 07:20 PM

Ok guys, for my next assignment I have to read from a binary file and then print out my information. I will post the assignment and what I have so far. But my question is, do I create the binary file first in the program or by hand or what?? I have read from a text file before but never a binary file.

1) Modify your program to read the initial list of cars in inventory from a data file that you create. It must read the saved cars into your array as it loads. The file must be stored in binary.

2) Once again. The file must be stored in binary.

3) The program must check for problems opening the binary data file and give an appropriate message to the user if it cannot open the file.

4) If the program doesn’t change the cars in the array in any way (I think they all do but just in case the one you select does not,) prompt the user for a change to the make and model of the second car in the array.

5) At the end of the program save the cars to the binary data file for the next program run.

Class


#include <iostream>
#include <fstream>
#include <iomanip>
#include <functional>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;

//Vehicle Class
class Car
{
protected:
    string make;  //make
    string model; // model
    string color;  // color
    int    year;  // year
    int mileage;  // miles on car

public:
        //Constructor that will set information for a new car
    void New_vehicle (string a, string b, string c, int d, int e)
    {make = a; model = b; color = c; year = d; mileage = e;;}
   
    Car(); //Default constructor
    Car(string, string, string, int, int);
    //mutator and accessor functions
    void setMake(string);
    void setModel(string);
    void setColor(string);
    void setYear(int);
    void setMileage(int);


    string getMake();
    string getModel();
    string getColor();
    int getYear();
    int getMileage();


    //Check mileage to see if valid
    void valid_mileage(int);
    void car_details();
    string string_car_details();
};

//Sets to default values
Car::Car() {
    make = " ";
    model = " ";
    color = " ";
    year = 0;
    mileage = 0;
}
    // My Vehicle set up(Make, model, color, year, type,bedsize, bike, mileage)
Car::Car(string make, string model, string color, int year, int mileage) {
    Car::make =  make;
    Car::model = model;
    Car::color = color;
    Car::year = year;
    valid_mileage(mileage);

}

void Car::setMake(string make) {
    Car::make = make;
}

void Car::setModel(string model) {
    Car::model = model;
}

void Car::setColor(string color) {
    Car::color = color;
}

void Car::setYear(int year) {
    Car::year = year;
}

void Car::setMileage(int mileage) {
    valid_mileage(mileage);
}


string Car::getMake() {
    return make;
}
string Car::getModel() {
    return model;
}
string Car::getColor() {
    return color;
}
int Car::getYear() {
    return year;
}
int Car::getMileage() {
    return mileage;
}


void Car::valid_mileage(int mileage) {
    if (mileage>=0)
        Car::mileage=mileage;
    else {
        Car::mileage=0;
        cout << "WARNING! You have entered invalid mileage!\n";
    }
    }

    void Car::car_details() {
        cout << "The current car is a " << year << ' ' << color << ' '
            << make << ' ' << model << " with " << mileage << " miles.\n\n";
    }



    string Car::string_car_details() {
        stringstream buf;
        buf << "The current car is a " << year << ' ' << color << ' '
        << make << ' ' << model << " with " << mileage << " miles.\n\n";
        return buf.str();
    }






CPP

#include "CarClass.h"
#include <fstream>
#include <sys/stat.h>

using namespace std;

ifstream::pos_type size;
char * memblock;

int main () {
  ifstream file ("read.bin", ios::in|ios::binary|ios::ate);
  if (file.is_open())
  {
    size = file.tellg();
    memblock = new char [size];
    file.seekg (0, ios::beg);
    file.read (memblock, size);
    file.close();

    cout << "the complete file content is in memory";

    delete[] memblock;
  }
  else cout << "Unable to open file";
  return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Reading and writing binary file c++

#2 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,456
  • Joined: 16-May 09

Re: Reading and writing binary file c++

Posted 19 March 2010 - 02:12 AM

When you open a file stream, the file is created if it does not exist, or you can add the truncate option if you like, to overwrite any existing file with that name.
fstream file("filename.ext", ios::binary|ios::in|ios::out); //open the file for input/output in binary mode
if(file.is_open())
    cout<<"File opened successfully!"<<endl;
//output the content
out.write(buffer.c_str(), buffer.size()); //buffer is a STL string containing the data to write
out.close(); //don't forget to close the streams you opened.


For a reference, visit [ Here ].
Was This Post Helpful? 1
  • +
  • -

#3 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 19 March 2010 - 06:50 AM

Ok cool! But do I need to put my array of cars into this binary file manually or is it best to at the start of my program write them in, then read them, then make my changes and save the new binary file??
Was This Post Helpful? 0
  • +
  • -

#4 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 19 March 2010 - 07:50 AM

In our program he wants us to take an array of 3 cars, and then write them to a binary file! My question is, how will I write an array of strings and ints to a binary file??
Was This Post Helpful? 0
  • +
  • -

#5 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 20 March 2010 - 10:32 PM

Ok guys, I spent all of yesterday understanding a binary file and creating a binary file's and I have managed to understand them pretty well and found some great websites explaining them. I have finished my code and it does not work, but I know whats wrong, I just need to know how to fix it!! I will post the code and then post my problem at the end!

Class
#include <iostream>
#include <fstream>
#include <iomanip>
#include <functional>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;

//Vehicle Class
class Car
{
protected:
		char make[40];	//Make of car
      	char model[40];	//Model of car
      	char color[20];	//Color of car
      	int year;		//Year of car
      	int mileage;	//Mileage of car

public:

	Car(); //Default constructor
	Car(char, char, char, int, int);
	//mutator and accessor functions
	void setMake(char);
    void setModel(char);
    void setColor(char);
    void setYear(int);
	void setMileage(int);


    char getMake();
    char getModel();
    char getColor();
    int getYear();
    int getMileage();


	//Check mileage to see if valid
    void valid_mileage(int);
    void car_details();
    string string_car_details();
};

//Sets to default values
Car::Car() {
	make = " ";
    model = " ";
    color = " ";
    year = 0;
    mileage = 0;
}
	// My Vehicle set up(Make, model, color, year, type,bedsize, bike, mileage)
Car::Car(char, char model, char color, int year, int mileage) {
	Car::make =  make;
	Car::model = model;
	Car::color = color;
	Car::year = year;
    valid_mileage(mileage);

}

void Car::setMake(char make) {
    Car::make = make;
}

void Car::setModel(char model) {
    Car::model = model;
}

void Car::setColor(char color) {
    Car::color = color;
}

void Car::setYear(int year) {
    Car::year = year;
}

void Car::setMileage(int mileage) {
    valid_mileage(mileage);
}


char Car::getMake() {
    return make;
}
char Car::getModel() {
    return model;
}
char Car::getColor() {
    return color;
}
int Car::getYear() {
    return year;
}
int Car::getMileage() {
    return mileage;
}


void Car::valid_mileage(int mileage) {
    if (mileage>=0)
        Car::mileage=mileage;
    else {
        Car::mileage=0;
        cout << "WARNING! You have entered invalid mileage!\n";
	}
    }

	void Car::car_details() {
	    cout << "The current car is a " << year << ' ' << color << ' '
			<< make << ' ' << model << " with " << mileage << " miles.\n\n";
	}



	string Car::string_car_details() {
	    stringstream buf;
	    buf << "The current car is a " << year << ' ' << color << ' '
	    << make << ' ' << model << " with " << mileage << " miles.\n\n";
	    return buf.str();
	}



CPP File
#include "CarClass.h"
#include <fstream>
#include <sys/stat.h>

using namespace std;

ifstream::pos_type size;
char * memblock;

int main () {

	struct record
	{

      char make[40];
      char model[40];
      char color[20];
      int year;
      int mileage;
      };


	const int SIZE = 3;
			
	//Array of 9 cars
	Car Car_array[SIZE] = { Car("Porsche", "911", "Silver", 2005, 18990), 
							Car("Ford", "Mustang", "Red", 2007, 49842),
							Car("Chevrolet", "Beretta", "Black", 1989, 90332)};


      ofstream out("filename.bin", ios::binary);
      struct record r[3];
      // write three cars
	  out.write( (char*)r, sizeof(struct record) * 3);

      // read 3 cars
      ifstream in("filename.bin", ios::binary);
      in.read( (char *)r, sizeof(struct record) * 3);
  return 0;
}



PROBLEM:
//Sets to default values
Car::Car() {
	make = " ";
    model = " ";
    color = " ";
    year = 0;
    mileage = 0;
}



What will I set the char's make, model, and color = to??

This post has been edited by tarheelfan_08: 21 March 2010 - 12:18 AM

Was This Post Helpful? 0
  • +
  • -

#6 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 21 March 2010 - 12:21 AM

Oh and when I hover over make, model or color, it says "Expression must be modifiable lvalue"
Was This Post Helpful? 0
  • +
  • -

#7 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 21 March 2010 - 12:55 AM

1>------ Build started: Project: FileReading, Configuration: Debug Win32 ------
1> Car.cpp
1>\filereading\carclass.h(48): error C2440: '=' : cannot convert from 'const char [14]' to 'char [40]'
1> There is no context in which this conversion is possible
1>\filereading\carclass.h(49): error C2440: '=' : cannot convert from 'const char [14]' to 'char [40]'
1> There is no context in which this conversion is possible
1>\filereading\carclass.h(50): error C2440: '=' : cannot convert from 'const char [14]' to 'char [20]'
1> There is no context in which this conversion is possible
1>\filereading\carclass.h(56): error C2106: '=' : left operand must be l-value
1>\filereading\carclass.h(57): error C2440: '=' : cannot convert from 'char' to 'char [40]'
1> There are no conversions to array types, although there are conversions to references or pointers to arrays
1>\filereading\carclass.h(58): error C2440: '=' : cannot convert from 'char' to 'char [20]'
1> There are no conversions to array types, although there are conversions to references or pointers to arrays
1>\filereading\carclass.h(65): error C2440: '=' : cannot convert from 'char' to 'char [40]'
1> There are no conversions to array types, although there are conversions to references or pointers to arrays
1>\filereading\carclass.h(69): error C2440: '=' : cannot convert from 'char' to 'char [40]'
1> There are no conversions to array types, although there are conversions to references or pointers to arrays
1>\filereading\carclass.h(73): error C2440: '=' : cannot convert from 'char' to 'char [20]'
1> There are no conversions to array types, although there are conversions to references or pointers to arrays
1>\filereading\carclass.h(86): error C2440: 'return' : cannot convert from 'char [40]' to 'char'
1> There is no context in which this conversion is possible
1>\filereading\carclass.h(89): error C2440: 'return' : cannot convert from 'char [40]' to 'char'
1> There is no context in which this conversion is possible
1>\filereading\carclass.h(92): error C2440: 'return' : cannot convert from 'char [20]' to 'char'
1> There is no context in which this conversion is possible
1>\filereading\car.cpp(24): error C2665: 'Car::Car' : none of the 3 overloads could convert all the argument types
1> \filereading\carclass.h(24): could be 'Car::Car(char,char,char,int,int)'
1> while trying to match the argument list '(const char [8], const char [4], const char [7], int, int)'
1>\filereading\car.cpp(25): error C2665: 'Car::Car' : none of the 3 overloads could convert all the argument types
1> \filereading\carclass.h(24): could be 'Car::Car(char,char,char,int,int)'
1> while trying to match the argument list '(const char [5], const char [8], const char [4], int, int)'
1>\filereading\car.cpp(26): error C2665: 'Car::Car' : none of the 3 overloads could convert all the argument types
1> \filereading\carclass.h(24): could be 'Car::Car(char,char,char,int,int)'
1> while trying to match the argument list '(const char [10], const char [8], const char [6], int, int)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Was This Post Helpful? 0
  • +
  • -

#8 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 21 March 2010 - 01:12 AM

Ok guys, I figured it out.

//Sets to default values
Car::Car() {
    strcpy (make, "UNINITIALIZED");
    strcpy (model, "UNINITIALIZED");
    strcpy (color, "UNINITIALIZED");
    year = 0;
    mileage = 0;
}
    // My Vehicle set up(Make, model, color, year, type,bedsize, bike, mileage)
Car::Car(char make, char model, char color, int year, int mileage) {
    Car::make =  make;
    Car::model = model;
    Car::color = color;
    Car::year = year;
    valid_mileage(mileage);

}




    // My Vehicle set up(Make, model, color, year, type,bedsize, bike, mileage)
Car::Car(char make, char model, char color, int year, int mileage) {
    Car::make =  make;
    Car::model = model;
    Car::color = color;
    Car::year = year;
    valid_mileage(mileage);

}


But now I am getting errors with the second part! Does anyone know if I will have to do something similar or what??
Was This Post Helpful? 0
  • +
  • -

#9 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Reading and writing binary file c++

Posted 21 March 2010 - 07:48 AM

View Posttarheelfan_08, on 21 March 2010 - 12:32 AM, said:

PROBLEM:
//Sets to default values
Car::Car() {
	make = " ";
    model = " ";
    color = " ";
    year = 0;
    mileage = 0;
}



What will I set the char's make, model, and color = to??



try this:
//Sets to default values
Car::Car() : 
    make("Unknown"), 
    model("Unknown"), 
    color("Unknown"), 
    year(1908), //Year the Model-T was invented
    mileage(0) { }



This constructor uses an initialization list to initialize the members.
Was This Post Helpful? 0
  • +
  • -

#10 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 21 March 2010 - 09:40 AM

Ok here is my new code guys, and it is creating the file that I want! But its not reading from that file and printing on the screen! IT should write the array of cars to the file, read the array of cars and print them on the screen and then re-write the array of cars..

Also, should I save this as a .bin file or a .dat file or .txt file or what??
CLASS
#include <iostream>
#include <fstream>
#include <iomanip>
#include <functional>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <sstream>

#include <sys/stat.h>


using namespace std;

//Vehicle Class
class Car
{
protected:
    char make[40];	//Make of car
    char model[40];	//Model of car
    char color[20];	//Color of car
    int year;		//Year of car
    int mileage;	//Mileage of car

public:

    Car(); //Default constructor
    Car(char* make, char* model, char* color, int, int);
    //mutator and accessor functions
    void setMake(char*);
    void setModel(char*);
    void setColor(char*);
    void setYear(int);
    void setMileage(int);


    const char* getMake();
    const char* getModel();
    const char* getColor();
    int getYear();
    int getMileage();


    //Check mileage to see if valid
    void valid_mileage(int);
    void car_details();
    string string_car_details();
};

//Sets to default values
Car::Car() 
{
    strcpy(make,"Uninitialzed");
    strcpy(model,"Uninitialzed");
    strcpy(color,"Uninitialzed");
    year = 0;
    mileage = 0;
}
// My Vehicle set up(Make, model, color, year,  mileage)
Car::Car(char* make, char* model, char* color , int year, int mileage) 
{
    strcpy(Car::make,make);
    strcpy (Car::model,model);
    strcpy(Car::color,color);
    Car::year = year;
    valid_mileage(mileage);

}

void Car::setMake(char* make) 
{
    strcpy(Car::make,make);
}

void Car::setModel(char* model) 
{
    strcpy(Car::model,model);
}

void Car::setColor(char* color) 
{
    strcpy(Car::color,color);
}

void Car::setYear(int year) 
{
    Car::year = year;
}

void Car::setMileage(int mileage) 
{
    valid_mileage(mileage);
}


const char* Car::getMake()  
{
    return make;
}
const char* Car::getModel() 
{
    return model;
}
const char* Car::getColor() 
{
    return color;
}
int Car::getYear() 
{
    return year;
}
int Car::getMileage() 
{
    return mileage;
}


void Car::valid_mileage(int mileage) 
{
    if (mileage>=0)
        Car::mileage=mileage;
    else 
    {
        Car::mileage=0;
        cout << "WARNING! You have entered invalid mileage!\n";
    }
}

void Car::car_details() 
{
    cout << "The current car is a year" << year << ' ' << color << ' '
        << make << ' ' << model << " with " << mileage << " miles.\n\n";
}



string Car::string_car_details() 
{
    stringstream buf;
    buf << "The current car is a year " << year << ' ' << color << ' '
        << make << ' ' << model << " with " << mileage << " miles.\n\n";
    return buf.str();
}



CPP File
#include "CarClass.h"
#include <fstream>
#include <sys/stat.h>

using namespace std;


int main () {

	struct record
	{

      char make[40];
      char model[40];
      char color[20];
      int year;
      int mileage;
      };


	const int SIZE = 3;
			
	//Array of 9 cars
	Car Car_array[SIZE] = { Car("Porsche", "911", "Silver", 2005, 18990), 
							Car("Ford", "Mustang", "Red", 2007, 49842),
							Car("Chevrolet", "Beretta", "Black", 1989, 90332)};


      ofstream out("binaryFile.bin", ios::binary);
      struct record r[3];
      // write three cars
	  out.write( (char*)r, sizeof(struct record) * 3);

      // read 3 cars
      ifstream in("binaryFile.bin", ios::binary);
      in.read( (char *)r, sizeof(struct record) * 3);
  return 0;
}


Was This Post Helpful? 0
  • +
  • -

#11 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Reading and writing binary file c++

Posted 21 March 2010 - 09:50 AM

Where does struct record r[3]; get initialized?
Was This Post Helpful? 0
  • +
  • -

#12 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 21 March 2010 - 09:56 AM

struct record here is where I thought
Was This Post Helpful? 0
  • +
  • -

#13 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Reading and writing binary file c++

Posted 21 March 2010 - 10:00 AM

You've declared an array of 3 records. The records themselves are uninitialized.
Was This Post Helpful? 1
  • +
  • -

#14 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 21 March 2010 - 10:07 AM

That part looks the same as how I have it in other programs!
Was This Post Helpful? 0
  • +
  • -

#15 tarheelfan_08  Icon User is offline

  • D.I.C Regular

Reputation: -2
  • View blog
  • Posts: 256
  • Joined: 24-January 10

Re: Reading and writing binary file c++

Posted 21 March 2010 - 10:13 AM

When I add cout's to see what the program is doing it just runs them together and does nothing with the read.

#include "CarClass.h"
#include <fstream>
#include <sys/stat.h>

using namespace std;


int main () {

	struct record
	{

      char make[40];
      char model[40];
      char color[20];
      int year;
      int mileage;
      };


	const int SIZE = 3;
			
	//Array of 9 cars
	Car Car_array[SIZE] = { Car("Porsche", "911", "Silver", 2005, 18990), 
							Car("Ford", "Mustang", "Red", 2007, 49842),
							Car("Chevrolet", "Beretta", "Black", 1989, 90332)};

	cout << "Writing to file\n\n";
      ofstream out("binaryFile.bin", ios::binary);
      struct record r[3];
      // write three cars
	  out.write( (char*)r, sizeof(struct record) * 3);
	  out.close();


      // read 3 cars
	  cout << "Reading file\n\n";
      ifstream in("binaryFile.bin", ios::binary);
      in.read( (char *)r, sizeof(struct record) * 3);
  return 0;
}



Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3