# File I/O (Reading from a Random-Access File)

Discussion in 'C' started by VersEtreOuNe, Feb 12, 2008.

1. ### VersEtreOuNeNew Member

Joined:
Feb 12, 2008
Messages:
1
0
Trophy Points:
0
INFO:
The program should enter a circle radius and Id for that circle to a file, then it should search for that id and print the radius for that circle.

PROBLEM:
This program compiles but it's not searching properly.

Circle.h
Code:
```#ifndef CIRCLE_H
#define CIRCLE_H

#include <iostream>
#include <fstream>
using namespace std;

class Circle
{
friend ostream& operator <<(ostream& output, const Circle& aCircle);
friend istream& operator >>(istream& input, Circle& aCircle);

public:
Circle();
Circle(const Circle& aCircle);

void SetCircleId(int id)   { _circleId = id; }

int GetCircleId() const { return _circleId; }

private:
int     _circleId;
};

#endif

```
Circle.cpp
Code:
```#include "Circle.h"

Circle::Circle()
{
_circleId = 0;
}

{
_circleId = id;
}

Circle::Circle(const Circle& aCircle)
{
_circleId = aCircle._circleId;
}

ostream& operator <<(ostream& output, const Circle& aCircle)
{
output << "\n          ------------" << endl;
output << "          Id    radius" << endl;
output << "          ------------" << endl;
output << "          " << aCircle._circleId << "     " << aCircle._circleRadius << endl;
output << "          ------------" << "\n\n";

return (output);
}

istream& operator >>(istream& input, Circle& aCircle)
{
int quantity;
cout << "\nHow many circles do you want to add ";
input >> quantity;

for (int i = 0; i < quantity; ++i)
{
cout << "\n\nEnter the ID of Circle #" << (i + 1) << " : ";
input >> aCircle._circleId;

cout << "Enter Radius of Circle #" << (i + 1) << " : ";

cout << endl;
}

return (input);
}

```
main.cpp
Code:
```#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;

#include "Circle.h"

int main ()
{
Circle aCircle;
fstream file;
int option;

do
{
<< " (1) Add Circle(s) \n"
<< " (2) Find a Circle by ID \n"
<< " (3) Exit \n"
cin >> option;

switch (option)
{
case 1:
file.close();
file.clear();

file.open("Circle.dat", ios::out | ios::app | ios::binary);

if (!file)
{
cerr << "\n\nFailed to open file.\n\n";
system("PAUSE");
exit(1);
}
else
{
cin >> aCircle;
file.write(reinterpret_cast<char*> (&aCircle), sizeof(Circle));
}
break;

case 2:
file.close();
file.clear();

cout << "Enter id: ";
int id;
cin >> id;
aCircle.SetCircleId(id);

file.open("Circle.dat", ios::in | ios::app | ios::binary);

if (!file)
{
cerr << "\n\nFailed to open file.\n\n";
system("PAUSE");
exit(1);
}
else
{
file.seekg(id * sizeof(Circle), ios::beg);

cout << aCircle;
}
break;

case 3:
file.close();
cout << "\n\nG   o    o    D    B    y    E\n\n";
exit(0);
break;

default: