473,883 Members | 2,052 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reuse of File pointer

Digital Don
19 New Member
Hi,

I have been using C++ for the past 6 months and always had a problem of using the same IFSTREAM variable to read multiple files.

Expand|Select|Wrap|Line Numbers
  1. do//Repeat while quit not entered
  2. {
  3.     ipf.clear();
  4.     cout<<"\nGive file name (Q for Quit):";
  5.     cin>>ipf;
  6.  
  7.     ipfilename.open(ipf.c_str(),ifstream::in);
  8.  
  9.     //Not able to reuse the above pointer with new filename (ipf)
  10.  
  11.     if(ipfilename.fail())
  12.         . . .
  13.     else
  14.     {            
  15.         while(!ipfilename.eof())
  16.         {
  17.             getline(ipfilename,tempread);
  18.             ...
  19.         }
  20.         //ipfilename.clear();//Clearing the file pointer –Didn’t work 
  21.         ipfilename.close();//Closing the file
  22.     }        
  23. }while(!(ipf=="Q" || ipf=="quit" || ipf=="Quit" || ipf=="q"));
  24.  
Please help with problem...I searched a lot in google but couldnt find the solution...

I asked a few friends and they gave me an option of using an array of File Pointers instead of reading...which is a waste of memory I feel. I want to know Why am not able to use this way...what am I doing wrong...

Hoping for solutions...

will be great if solved...

Thank You in advance....

Regards,
Digital Don
Feb 5 '07 #1
4 3196
macklin01
145 New Member
Good question.

On the one hand, the istream pointers probably wouldn't take _that_ much memory, but on the other hand, I agree that it's unsatisfactory that you can't take your approach. (Which I feel is more elegant.)

Are you sure this isn't a compiler bug? Have you tried another compiler?

Also, I'd recommend trying a smaller code snippet until you can track something down that works. e.g.,

Expand|Select|Wrap|Line Numbers
  1. ifstream inputfile; 
  2. for( int i=0 ; i < 200 ; i++ )
  3. {
  4.  inputfile.open( "testfile.txt", , ifstream::in );
  5.  inputfile.close();
  6. }
  7.  
See if that compiles and runs cleanly, first. Then, start adding in additional file operations.

Finally, another option you might consider is putting the ifstream constructory inside your loop. Then, the object will be deallocated from memory on each iteration, getting around any memory waste issues, and probably getting around any silly bugs.

At any rate, I find it useful to sometimes first test loops with many object creations and/or destructions and watch the memory useage. It can be very helpful for finding bugs, etc. (Although in that case, it's more for debugging my own classes, and not for searching for potential bugs in a compiler.)

Thanks, and good luck! -- Paul
Feb 7 '07 #2
Digital Don
19 New Member
Hi Macklin

Thank You for your response. I am using Visual Studio 2005 and in that I havent got any compiling error.

It compiles fine and reads input any number of times...

The loop works fine if an invalid filename is given. when first time a valid filename is given it works and reads it...when a different file name is provided it doesnt open the new file, instead it opens the first file or in case of ifstream constructor putting inside loop, it exits abruptly....

Why is what I wanna know.
Thanks again and Hope someone has solution for it...


Good question.

On the one hand, the istream pointers probably wouldn't take _that_ much memory, but on the other hand, I agree that it's unsatisfactory that you can't take your approach. (Which I feel is more elegant.)

Are you sure this isn't a compiler bug? Have you tried another compiler?

Also, I'd recommend trying a smaller code snippet until you can track something down that works. e.g.,

Expand|Select|Wrap|Line Numbers
  1. ifstream inputfile; 
  2. for( int i=0 ; i < 200 ; i++ )
  3. {
  4. inputfile.open( "testfile.txt", , ifstream::in );
  5. inputfile.close();
  6. }
  7.  
See if that compiles and runs cleanly, first. Then, start adding in additional file operations.

Finally, another option you might consider is putting the ifstream constructory inside your loop. Then, the object will be deallocated from memory on each iteration, getting around any memory waste issues, and probably getting around any silly bugs.

At any rate, I find it useful to sometimes first test loops with many object creations and/or destructions and watch the memory useage. It can be very helpful for finding bugs, etc. (Although in that case, it's more for debugging my own classes, and not for searching for potential bugs in a compiler.)

Thanks, and good luck! -- Paul
Feb 8 '07 #3
horace1
1,510 Recognized Expert Top Contributor
before you can use ipfilename again you need to clear the error condition from the eof of the previous file, e.g.
Expand|Select|Wrap|Line Numbers
  1.     do//Repeat while quit not entered
  2. {
  3.     ipf.clear();
  4.     cout<<"\nGive file name (Q for Quit):";
  5.     cin>>ipf;
  6.     cout << ipf << endl;
  7.     ipfilename.clear();   //  clear any error condition!
  8.     ipfilename.open(ipf.c_str(),ifstream::in);
  9.  
  10.     //Not able to reuse the above pointer with new filename (ipf)
  11.  
  12.     if(ipfilename.fail())
  13.        {
  14.         cout << "\nUnable to open file " << ipf << " " << strerror(errno);
  15.         cin.get();cin.get();
  16.         return 1;                                                 // open failed
  17.         }
  18.      else
  19.     {            
  20.         while(!ipfilename.eof())
  21.         {
  22.             getline(ipfilename,tempread);
  23.             cout << tempread << endl;
  24.         }
  25.         //ipfilename.clear();//Clearing the file pointer –Didn’t work ?
  26.         ipfilename.close();//Closing the file
  27.     }        
  28. }while(!(ipf=="Q" || ipf=="quit" || ipf=="Quit" || ipf=="q"));
  29.  
Feb 8 '07 #4
Digital Don
19 New Member
Thank You Man...I used Clear at the end before close and it worked fine...


before you can use ipfilename again you need to clear the error condition from the eof of the previous file, e.g.
Expand|Select|Wrap|Line Numbers
  1. do//Repeat while quit not entered
  2. {
  3.     ipf.clear();
  4.     cout<<"\nGive file name (Q for Quit):";
  5.     cin>>ipf;
  6.     cout << ipf << endl;
  7.     ipfilename.clear(); // clear any error condition!
  8.     ipfilename.open(ipf.c_str(),ifstream::in);
  9.  
  10.     //Not able to reuse the above pointer with new filename (ipf)
  11.  
  12.     if(ipfilename.fail())
  13. {
  14. cout << "\nUnable to open file " << ipf << " " << strerror(errno);
  15. cin.get();cin.get();
  16. return 1; // open failed
  17. }
  18.     else
  19.     {            
  20.         while(!ipfilename.eof())
  21.         {
  22.             getline(ipfilename,tempread);
  23.             cout << tempread << endl;
  24.         }
  25.         //ipfilename.clear();//Clearing the file pointer –Didn’t work ?
  26.         ipfilename.close();//Closing the file
  27.     }        
  28. }while(!(ipf=="Q" || ipf=="quit" || ipf=="Quit" || ipf=="q"));
  29.  
Feb 9 '07 #5

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

Similar topics

3
6903
by: DPfan | last post by:
What's exactly the meaning of "code reuse" in C++? Why such kind of reuse have more advantages over the counterpart in other language like in C? How is "code reuse" realized in C++? By composition mainly? What're others? Thanks in advance for your comments!
11
3535
by: Damon | last post by:
Hi, Can someone point out to me what's wrong with the code below? I'm trying to reuse the deleted pointer but it won't compile. My reason may be wrong, but I thought reusing the pointer would save the trouble of declaring a pointer to a string array. I also suspect there will be a problem of releasing memory in the way I'm using the array pointer and is toying with using a vector<std::string> instead. Anyway, thanks for any pointers...
3
1290
by: danra | last post by:
Hi, I have a question which seems to me pretty basic, unfortunately I can't seem to figure it out. Let's say I have an abstract base class Vehicle and classes Car and Truck which derive from it. Let's say I have abstract base class A which contains a list of vehicles, and I define a method to insert and handle a vehicle into
7
2842
by: hank | last post by:
Hi All In the Circular Logging when the Primary Log file fill up, the database manager will creat a secondary log files for the transaction; when this transaction finished, the secondary log files still allocated in log directory; when all application disconnect from database or database reactive or database restart the secondary log files will be deleted from log directory. For each transaction log request, database manager always...
48
5879
by: avasilev | last post by:
Hi all, my question is: if i allocate some memory with malloc() and later free it (using free()), is there a possibility that a consequent malloc() will allocate memort at the same starting address and will return the same pointer as the previous malloc(). I would like to have confirmation on whether this is practically a concern when pointers are used to uniquely identify data structure instances - like in this example:
4
1575
by: sam | last post by:
hello all, pretty straightforward question here, i think. i'm experimenting with classes and have written a File class that looks like it's worth keeping for future use. however, i cannot work out where to put it for this purpose or how to get it in. i figured i'd try a bit of (un)inspired guesswork by putting it in my module folder, appending sys.path to tell the interpreter where this was, and importing it like a module. probably...
19
2395
by: jacob navia | last post by:
There is an interesting discussion running in Slashdot now, about code reuse. The thema of the discussion is here: < quote > Susan Elliot Sim asks: "In the science fiction novel, 'A Deepness in the Sky,' Vernor Vinge described a future where software is created by 'programmer archaeologists' who search archives for existing pieces of code, contextualize them, and combine them into new applications. So
8
2213
by: WebSnozz | last post by:
I have an application written in C that does a lot of low level stuff. It does a lot of things like casting from void*'s. I want to create a new GUI for it in either C# or MC++, but reuse the existing code. The options I've considered so far: 1. Create a new MC++ GUI project and add the *.c files to them and mark them with pragma unamanged. However, the /clr option does not compile *.c files, so I rename them to *.cpp, and now they...
13
3984
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help is much appreciated. JD
0
9945
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10763
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...
1
10863
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10422
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...
0
9586
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5807
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
6006
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4229
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3241
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.