473,836 Members | 1,858 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with file handling in c++

23 New Member
I have a problem working with files in c++.This is my code for modifying a record in a file.When i execute it ,it doesn't check rec in file & comes out .What's wrong???
Many time working with file(adding record &then printing on screen or after deletion print the rec )last rec is read twice or otherwise each rec ie read twice I have checked my code.Still it's not working Pls help me If u can give correct code it will help me.


Expand|Select|Wrap|Line Numbers
  1. #include<fstream.h>
  2. #include<conio.h>
  3. #include<stdio.h>
  4. #include<string.h>
  5. #include<process.h>
  6. class emp
  7. {
  8.     int id;
  9.     char name[20];
  10.     float sal;
  11. public:
  12.  
  13.     void getdata()
  14.     {
  15.          cout<<"Enter id:="<<"\n";
  16.          cin>>id;
  17.          cout<<"Enter name:="<<"\n";
  18.          cin>>name;
  19.          cout<<"Enter salary:="<<"\n";
  20.          cin>>sal;
  21.     }
  22.     void putdata()
  23.     {
  24.          cout<<"Id      :="<<"\t "<<id<<endl;
  25.          cout<<"Name    :="<<"\t "<<name<<endl;
  26.          cout<<"Salary  :="<<"\t "<<sal<<endl;
  27.     }
  28.     int getid()
  29.     {
  30.     return id;
  31.     }
  32.     void modify();
  33. }e1,emp1;
  34. void emp::modify()
  35. {
  36.     cout<<"Emp  id" <<id<<"\t";
  37.     cout<<"Emp  name" <<name<<"\t";
  38.     cout<<"Emp  Salary" <<sal<<"\n";
  39.     cout<<"Enter new details "<<endl;
  40.     char nm[20]=" ";
  41.     int sal1;
  42.     cout<<"New Name :(enter  '.' to retain old one)";
  43.     cin>>nm;
  44.     cout<<"New Salary :(enter  '-1' to retain old one)";
  45.     cin>>sal1;
  46.     if(strcmp(nm,".")!=0)
  47.         strcpy(name,nm);
  48.     if(sal1!=-1)
  49.         sal=sal1;
  50. }
  51.  
  52. void main()
  53. {
  54.     long pos;
  55.     char found='f';
  56.     int id1;
  57.     clrscr();
  58.     fstream fio;
  59.     fio.open("emp.dat",ios::app|ios::out|ios::binary);
  60.     emp1.getdata();
  61.     fio.write((char *)&emp1,sizeof (emp1));
  62.     cout<<"The contents before modification \n";
  63.     while(!fio.eof())
  64.     {
  65.         fio.read((char *)&emp1,sizeof (emp1));
  66.         emp1.putdata();
  67.     }
  68.     cout<<"Enter id of an Emploee whose record is to be modified "<<endl;
  69.     cin>>id1;
  70.     fio.seekg(0);
  71.  
  72.     while(fio)
  73.     {
  74.         pos=fio.tellg();
  75.         fio.read((char *)&e1,sizeof (e1));
  76.  
  77.         if(e1.getid()==id1)
  78.         {
  79.             e1.modify();
  80.             fio.seekg(pos);
  81.             fio.write((char *)&e1,sizeof(e1));
  82.             found='t';
  83.             break;
  84.         }
  85.     }
  86.     if(found=='f')
  87.         cout<<"Record not found !!\n";
  88.     fio.seekg(0);
  89.     cout<<"Now the contents \n";
  90.     while(!fio.eof())
  91.     {
  92.         fio.read((char *)&emp1,sizeof (emp1));
  93.         emp1.putdata();
  94.     }
  95.     fio.close();
  96. getch();
  97. }
Oct 6 '07 #1
8 2662
Ganon11
3,652 Recognized Expert Specialist
I didn't exactly understand the problems you were having - could you please explain them in better detail?
Oct 6 '07 #2
ashwini1680
23 New Member
The code is for modyfying a record in an existing file
So i have taken emp id from user & then that id is searched in a file.If it matches with the id of any re in file whole rec is modified.But when i wrote loop for traversing throug rec in file it shows rec not found.I traced my program n i found that it doesn't go inside the loop even if rec are present in file
I hope my question is clear now n i will get solution for it.
Also while printing rec from files last rec is repeated .why?
Oct 6 '07 #3
Ganon11
3,652 Recognized Expert Specialist
I don't know what to tell you - it looks like you are using legacy C style functions with seekg and tellg, etc. I normally use the subclasses ifstream and ofstream for my file work - they function just like cin and cout, respectively, but with files.
Oct 7 '07 #4
ashwini1680
23 New Member
i have also used ifstream & ofstream.But in case of modification we have to write the new rec in position where the old rec was.That's why before reading every rec its position in file(using tellg())in terms of byteno is taken & then file pointer is moved at that byte no(using seekg()) & the rec is written in file using write fun.That's what the logic is I don't understand what's wrong in it.In book also the program is written like this?If this willnot work then what's the alternative.Ple ase help me with code.I need it badly.
Oct 9 '07 #5
ymprogenius
2 New Member
according to me you shud use "input" mode instead of "append" mode for openning the file because when it checks for end of file it is already in end due to append mode.
Oct 26 '07 #6
tracethepath
15 New Member
i can help u with your problem that the last record repeats twice.

Your loop says:

Expand|Select|Wrap|Line Numbers
  1.   while there is no file failure (eof):
  2.     abc <-- read next record
  3.     display abc
  4.  
What happens is this:
Read record one (no file read failure), display record one.
Read record two (no file read failure), display record two.
...
Read record N (no file read failure), display record N.
Read record N+1 (couldn't: file read failure), display record N (since abc == last record)
While loop terminates.

You need to test the file failure before displaying the record. There are a zillion ways to rewrite this, so I offer my way:

Expand|Select|Wrap|Line Numbers
  1. while (true)
  2. {
  3.   if (! file.read( ... )) break;
  4.   abc.showdetails();
  5.   cout <<endl;
  6. }
  7.  
Hope this helps.
Oct 27 '07 #7
ymprogenius
2 New Member
Hav a look at my code actually its not written specially for u its a part of my banking project
ignore cprintf () ,gotoxy() ,box() ,mainmenu() and textbackground( )etc from this program,coz they are just for presentation.

here is the code
Dec 20 '07 #8
Ganon11
3,652 Recognized Expert Specialist
ymprogenius;

You have done what is called 'thread hijacking' - stealing someone else's thread to ask your own, unrelated question. In addition, you have failed to clearly outline what problem you have, instead merely saying "check my code." We're not your compiler, searching through code to find errors with no leads as to what might be wrong; you need to let us know what problems you are experiencing and what output you are expecting so we can better help you.

All this and more is found in our FAQ/Posting Guidelines, found under the 'Help' link at the top of your screen. Please read through these before re-posting your question in a new thread.
Dec 20 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

6
7746
by: Nimmi Srivastav | last post by:
Brief:- I am having trouble getting a FileWriter to write to a non-existent file if I instantiate the FileWriter with a String that is manipulated at run time. It works fine with a hard-coded char array. The error that I get in the former case is: (The specified path is invalid)tion Detailed:- This is my first serious foray into Java ----- I recently completed the Hello World program ----- so my apologies if I am not
9
3212
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is indeed also true for our language of choice, Python. Its file type allows some extraordinary convenient access like: for line in open("blah"): handle_line(line)
2
1384
by: Chris Fonnesbeck | last post by:
I thought I knew how to do error handling in python, but apparently I dont. I have a bunch of code to calculate statistical likelihoods, and use error handling to catch invalid parameters. For example, for the bernoulli distribution, I have: def bernoulli_like(self, x, p, name='bernoulli'): """Bernoulli log-likelihood""" # Ensure proper dimensionality of parameters dim = shape(x)
8
5232
by: dbuser | last post by:
Hi, I need help on a problem, as described below. I am reading a file "input.txt"which has data like this: abc def gh izk lmnopq rst uvwxyz I am using fstream object to read the file and writing into a dynamic array. My problem is that the array shows extra z and probably because of this further processing gives run time error in borland compiler. Can you please tell me, if the problem is related to handling end-of line , how do i do...
5
424
by: learner | last post by:
I have datafiles like this: 0 1941 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.02 0.00 0.00 1 0 1941 0.00 0.03 0.00 0.03 0.04 0.02 0.00 0.00 0.00 0.00 2 0 1941 0.00 0.00 0.00 0.00 0.52 0.00 0.00 0.17 1.07 0.09 3 0 1941 0.04 0.00 0.00 0.00 0.00 0.62 0.00 0.01 0.00 0.00 4 0 1941 0.00 0.02 0.00 0.00 0.00 0.22 0.00 0.00 0.00 0.16 5 0 1941 0.00 0.00 0.00 0.00 0.09 0.04 0.00 0.00 0.00 0.00 6 0 1941 0.00...
5
7525
by: Karl | last post by:
Hi, I have some code that will save the contents of a Rich Text Box in either a Text or Rich Text Format file. The code is using the SaveFileDialog and is working correctly. I have been testing the code and added in some exception handling to cater for any problems. During testing I have found that if I attempt to save to a floppy disc that is full, a System.IO.IOException is raied with the message "There is not enough space on the...
10
4032
by: Charles Law | last post by:
For some reason, when I click the X to close my MDI parent form, the action appears to be re-directed to one of the MDI child forms, and the parent remains open. I am then unable to close the application. What should happen, is that the main MDI form should close, taking the child forms with it. There is code to loop through the child forms, remove the controls on each of them, and then close the form, but this code should execute only...
19
4787
by: rmr531 | last post by:
First of all I am very new to c++ so please bear with me. I am trying to create a program that keeps an inventory of items. I am trying to use a struct to store a product name, purchase price, sell price, and a taxable flag (a Y/N char) and then write this all out to a file (preferably just a plain old text file) and then read it in later so that I can keep a running inventory. The problem that I am running into is when I write to the...
8
2188
by: JDavis | last post by:
I am using System.Net.Sockets to connect a client socket to a server that requires three inputs when I connect: host, port and an identification number that identifies the person connecting. None of the overloads for either the Connect or BeginConnect methods takes that many inputs (basically they take host and port only). Would it be best to create a new class that derives from the base class System.Net.Sockets and implement a new...
5
6817
by: kailashchandra | last post by:
I am trying to upload a file in php,but it gives me error msg please Help me? My Code is like below:- i have one php file named upload.php and i have another html file named upload.html and inside html i am calling php file upload.php:- <?php
0
10818
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10526
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10237
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7770
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5641
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4436
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3999
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3094
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.