Infinite loop in binary file

Infinite loop not working

Page 1 of 1

1 Replies - 2243 Views - Last Post: 27 October 2009 - 12:52 AM Rate Topic: -----

#1 Ratatat   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 22-July 09

Infinite loop in binary file

Posted 26 October 2009 - 08:44 PM

What I'm trying to do is use an infinite loop to get the contents of a binary record that has already been made. When I enter one record number everything is displayed correctly. But after that The file will only display the contents of that first record. In fact, I can't even enter another record number because the file immediately prints what I've already seen and asks if I'd like to continue.

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

int get_value(int val);
char name[20];
int input = 0;

int main()
{
	
	char filename[81];
	int n;
	int age;
	int recsize = sizeof(name) + sizeof(int);
	
   
	cout<<"Please enter a filename: ";
	cin.getline(filename, 80);
	
	fstream fbin(filename, ios::binary | ios::out | ios::in);
	if (!fbin)
	{
			  cout<<"File could not be opened";
			  return -1;
	}

	while(1)
	{
	
	cout<<"Enter record number: ";
	n = get_value(0);
	fbin.seekp(n * recsize);
	
	fbin.read(name, 20);
	fbin.read(reinterpret_cast<char*>(&age), sizeof(int));
	
	
	cout<<"The name is: "<<name;
	cout<<"\nThe age is: "<<age<<endl;
	cout<<"Would you like to continue if not enter -1: ";
	cin>>input;
	
	if (input = -1)
	{
	  fbin.close();
	}
	}
  
	return 0;
}

int get_value(int val)
{
	char s[80];
	cin.getline(s, 79);
	if (strlen(s) == 0)
	{
		  return val;
	}
	return atoi(s);
}




Is This A Good Question/Topic? 0
  • +

Replies To: Infinite loop in binary file

#2 Guest_c.user*


Reputation:

Re: Infinite loop in binary file

Posted 27 October 2009 - 12:52 AM

save fbin.seekp(n * recsize); somewhere

	long offset;

	for (offset = 0; /* space */; ) { /* it is instead of while (1) */

...

		offset = offset+n*recsize;
		fbin.seekp(offset);


This post has been edited by c.user: 27 October 2009 - 12:53 AM

Was This Post Helpful? 0

Page 1 of 1