Question

Reading 10,000 records from a txt file

Asked by: w100ktn

I'm writing a simple program to read up to 10,000 records from a text file (about 500kB). I didn't have any problem reading up to 5000 records but if I have more than that, the program gets terminated.

Does anybody have any idea to work around this? I'm using Visual C++. Thanks a lot for any help you can give.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-11-03 at 20:03:10ID21194002
Topic

C++ Programming Language

Participating Experts
4
Points
50
Comments
18

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Text(txt) To Excel?
    Hi there, Does anybody has any idea how to convert text file (txt) to excel format using vb coding? I know how to convert text file to excel manually but now i want to code the converting in vb. Is it possible? Urgent. Thanks.
  2. Split records into text files (.txt)
    this is the content of before.txt ------------------------------------------------------------------- 000000 88880000 (text) (text) (text) **** 88880000 (text) (text) (text) (text) (text) **** 999999 --------------------------------------------------------------------- conten...
  3. Comparing records between a txt file and an Oracle table
    Hi, Every day we have to load a txt file (with just two columns) in a table. It's about 800,000 records. We do this in order to compare with Table_Master to know what records are matching. I'm wondering if you think there is another way to compare records between the txt file...
  4. Write Record To txt File
    i have got the data so it is saved into a txt file but can any one explain how to get it out and display the first record into a label3 here is my code Private Sub Command1_Click() With stock .ProductCode = product(0).Text .ProductName = product(1).Text .Prod...
  5. Multiple TXT records for a single domain - is this possible?
    Hi, I have a domain (eg. xxx.company.com) for which I need to add two TXT records in DNS. I have added one but the tool I am using will not allow me to add a second TXT record for the same domain, stating one already exists. I need to add two SFP TXT records (see below) x...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: OnegaZhangPosted on 2004-11-03 at 20:18:26ID: 12489975

It should work. protect your code by checking the data readed, if it is an empty line? Is every field  valid?

 

by: pb_indiaPosted on 2004-11-03 at 21:26:37ID: 12490451

Use new to allocate memory and then delete the memory by using delete after the record is read..
if u post the code I can help you to correct it.

 

by: pb_indiaPosted on 2004-11-03 at 21:32:28ID: 12490470

//For example:

string log_line;
ifstream log_file("access.log");

while(!log_file.eof())
{
   getline(log_file,log_line); // read a line of any length.
   cout<<log_line<<endl;
}
log_file.close();

 

by: itsmeandnobodyelsePosted on 2004-11-03 at 23:08:55ID: 12490750

>> the program gets terminated

Is there an access violation? Did you check with the debugger what happened?

You could make a try - catch block around, so you might get the error cause in the catch block. The code snippet from above looks fine - beside of the fact that outputting 10000 lines will last some time...

Regards, Alex

 

by: rstaveleyPosted on 2004-11-04 at 02:38:41ID: 12491987

> about 500kB

That sounds suspiciously like DOS (the dreaded 640K ceiling which leaves old timers hearabouts in cold sweats). You're not using Visual C 1.5 to generate a DOS executable, are you?

 

by: rstaveleyPosted on 2004-11-04 at 02:39:42ID: 12491995

> hearabouts

hereabouts   (the spelling mistake was symptomatic of a cold sweat)

 

by: itsmeandnobodyelsePosted on 2004-11-04 at 04:16:27ID: 12492742

>> Visual C 1.5 to generate a DOS executable

Do you mean Visual C++ 1.5.2 to generate a Win 3.xx executable?

There wasn't a 640K limit  in VC++ 1.x, but i remember that MFC CString allocated a minimum of 256 bytes (or more..) for any string. So 16 MB RAM wasn't enough to read 10000 CString objects from database...

Regards, Alex

 

by: itsmeandnobodyelsePosted on 2004-11-04 at 04:23:52ID: 12492790

>> So 16 MB RAM

Maybe it was  4 MB ;-)

Cold sweats seem to have different effects on different people ...

 

by: rstaveleyPosted on 2004-11-04 at 05:50:57ID: 12493420

MS DOS has (can we say had?) 640K of addressable conventional memory. A pointer could conveniently be used to address any 64K within that space but you would need to do clever things with far pointer arithmetic to address > 64K (recall huge pointers and pointer normalisation on far pointers... shudder). If you needed to address more than 640K, you needed to do clever things with extended or expanded memory. I'm not really up with version numbers of Microsoft C (I was a Turbo C fan back in those days), but I *think* that Microsoft's Visual C version 1 compilers were for DOS and Windows 3.x only. If you run a DOS executable on a Win32 platform, it runs in 8086 emulation, which means that you are back in the bad old days of 640K. I had no idea that they had things like CString back in those days. I expect the internal storage was in Cuniform :-)

 

by: w100ktnPosted on 2004-11-04 at 09:52:37ID: 12496156


//main.cpp
#include <stdio.h>
#include <string>
#include <fstream>
#include <iostream>

#include "record.h"

using namespace std;



string prefix;
string firstName;
string MiddleInit;
string lastName;

string title;
string company;
string department;
string address;
string city;
string state;
string zip1;
string zip2;

Record *record;

bool ReadFile(string Infilename, string Outfilename)
{
      ifstream filein;
      ofstream fileout;
      string temp;
      int pos;

      filein.open(Infilename.c_str(), ios::in);
      fileout.open (Outfilename.c_str (), ios::out);

      if ( filein.fail() )
      {
            cout << "Cannot open file to read." << endl;
            return false;
      }

      if ( fileout.fail() )
      {
            cout << "Cannot open file to save." << endl;
            return false;
      }

      int size = 0;


      while (!filein.eof() && size < 5000) //if I take out the size < 5000 or put in a number > 5000, the program got terminated with an error
      {
            getline(filein, temp);
            pos = temp.find (",", 0);
            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            prefix = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            firstName = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            MiddleInit = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            lastName = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            title = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            company = temp.substr (1, pos - 2);
            
            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            department = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            address = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            city = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            state = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            zip1 = temp.substr (1, pos - 2);

            temp.erase (0, pos + 1);
            pos = temp.find (",", 0);
            zip2 = temp.substr (1, pos - 2);

            record = new Record(prefix, firstName, MiddleInit, lastName, title, company, department, address, city, state, zip1, zip2);

            fileout << record->getPrefix() << " " << record->getfirstName() << " " << record->getMiddleInit() << " " << record->getlastName() << endl;
            if (record->getTitle() !="")
                  fileout << record->getTitle() << endl;
            fileout << record->getCompany() << endl;
            if (record->getDept() !="")
                  fileout << record->getDept() << endl;
            fileout << record->getAdd() << endl;
            fileout << record->getCity() << " " << record->getState() << " " << record->getZip1() << "-" << record->getZip2() << endl << endl;
            
            size++;
            delete record;

      }

}      


void main()
{
      string Infilename, Outfilename;
      cout << "Enter a file name to read: ";
      cin >> Infilename;
      cout << "Enter a file name to save: ";
      cin >> Outfilename;
      bool success = ReadFile (Infilename, Outfilename);


}


//record.h
#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

class Record
{
private:
      string prefix;
      string firstName;
      string MiddleInit;
      string lastName;
      string title;
      string company;
      string department;
      string address;
      string city;
      string state;
      string zip1;
      string zip2;
public:
      Record( const string str1 = "",  const string str2 ="" ,  const string str3 ="",  const string str4 ="",  const string str5 ="",  const string str6="",  const string str7="",  const string str8="",  const string str9="",  const string str10="",  const string str11="", const string str12="")
      {
            prefix = str1;
            firstName = str2;
            MiddleInit = str3;
            lastName = str4;
            title = str5;
            company = str6;
            department = str7;
            address = str8;
            city = str9;
            state = str10;
            zip1 = str11;
            zip2 = str12;
      }
      set( const string str1,  const string str2,  const string str3,  const string str4,  const string str5,  const string str6,  const string str7,  const string str8,  const string str9,  const string str10,  const string str11, const string str12)
      {
            prefix = str1;
            firstName = str2;
            MiddleInit = str3;
            lastName = str4;
            title = str5;
            company = str6;
            department = str7;
            address = str8;
            city = str9;
            state = str10;
            zip1 = str11;
            zip2 = str12;
      }
      string getPrefix()
      {
            return prefix;
      }

      string getfirstName()
      {
            return firstName;
      }

      string getMiddleInit()
      {
            return MiddleInit;
      }

      string getlastName()
      {
            return lastName;
      }

      string getTitle()
      {
            return title;
      }

      string getCompany()
      {
            return company;
      }

      string getDept()
      {
            return department;
      }

      string getAdd()
      {
            return address;
      }

      string getCity()
      {
            return city;
      }

      string getState()
      {
            return state;
      }

      string getZip1()
      {
            return zip1;
      }

      string getZip2()
      {
            return zip2;
      }


};



This is how the input file looks like. It has a few thousands lines like this. I don't know how the users get this file, but this will be the input to my program.

"00000001","MS","D","L","GOLDFARB","","DIRECTOR","INSTITUE OF MANAGEMENT & ADMIN","DEPT 82216","29 W 35TH ST","NEW YORK","NY","10001","2299",""
"01759019","MR","RICH","","MULHOLAND","","PURCHASING AGENT","J L STRUCTURAL INC","","111 STATION ST","ALIQUIPPA","PA","15001","3610",""

My error says "abnormal program termination". If I hit "Retry" then the outputs still come out correctly. But I would lile to have the users not see this error. Is there any way you know of, please?

Thank you very much for your help.



 

by: pb_indiaPosted on 2004-11-04 at 11:14:14ID: 12497056

I got your code to work. I have to test against the actual file that has more than 5000 records. Can you mail me the file that has all the comma separated records information. Above is just 2 records.

mail at pb_india AT HOTMAIL DOT COM

 

by: pb_indiaPosted on 2004-11-04 at 11:20:42ID: 12497114

Meanwhile try this:
Replace your record.cpp with this one. Let me know how it goes.
//main.cpp
#include <stdio.h>
#include <string>
#include <fstream>
#include <iostream>

#include "record.h"

using namespace std;



string prefix;
string firstName;
string MiddleInit;
string lastName;

string title;
string company;
string department;
string address;
string city;
string state;
string zip1;
string zip2;

Record *record=NULL;
void clearIT(void){
 prefix.erase();
 firstName.erase();
 MiddleInit.erase();
 lastName.erase();

 title.erase();
 company.erase();
 department.erase();
 address.erase();
 city.erase();
 state.erase();
 zip1.erase();
 zip2.erase();

}
bool ReadFile(string Infilename, string Outfilename)
{
     ifstream filein;
     ofstream fileout;
     string temp="";
     int pos=0;

     filein.open(Infilename.c_str(), ios::in);
     fileout.open (Outfilename.c_str (), ios::out);

     if ( filein.fail() )
     {
          cout << "Cannot open file to read." << endl;
          return false;
     }

     if ( fileout.fail() )
     {
          cout << "Cannot open file to save." << endl;
          return false;
     }

     int size = 0;


     while (!filein.eof() )
     {
                  clearIT();
          getline(filein, temp);
          pos = temp.find (",", 0);
          temp.erase (0, pos + 1);
          pos = temp.find (",", 0);
          if(pos>2){
                    prefix = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    firstName = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    MiddleInit = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    lastName = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    title = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    company = temp.substr (1, pos - 2);
         
                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    department = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    address = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    city = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    state = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    zip1 = temp.substr (1, pos - 2);

                    temp.erase (0, pos + 1);
                    pos = temp.find (",", 0);
                    zip2 = temp.substr (1, pos - 2);
              }
          record = new Record(prefix, firstName, MiddleInit, lastName, title, company, department, address, city, state, zip1, zip2);

          fileout << record->getPrefix() << " " << record->getfirstName() << " " << record->getMiddleInit() << " " << record->getlastName() << endl;
          if (record->getTitle() !="")
               fileout << record->getTitle() << endl;
          fileout << record->getCompany() << endl;
          if (record->getDept() !="")
               fileout << record->getDept() << endl;
          fileout << record->getAdd() << endl;
          fileout << record->getCity() << " " << record->getState() << " " << record->getZip1() << "-" << record->getZip2() << endl << endl;
         
          size++;
              if(record){
                  delete record;
                  record=NULL;
              }
              temp.erase();

     }

}    


void main()
{
     string Infilename, Outfilename;
     cout << "Enter a file name to read: ";
     cin >> Infilename;
     cout << "Enter a file name to save: ";
     cin >> Outfilename;
     bool success = ReadFile (Infilename, Outfilename);


}

 

by: itsmeandnobodyelsePosted on 2004-11-04 at 11:57:36ID: 12497485

 while (!filein.eof() )
     {
         getline(filein, temp);

That sequence looks wrong as you don't check getline error. At end-of-file the last call to getline() most probably fails, what sets the stream status to fail and not to eof. The condition size < 5000 simply prevents your prog from reaching file end.

I would suggest to try that:

    while (!getline(filein, temp))
    {
         ...

Regards, Alex


     

 

by: itsmeandnobodyelsePosted on 2004-11-04 at 12:01:35ID: 12497524

Sorry,

     while (getline(filein, temp))

of course.

Regards, Alex

   

 

by: itsmeandnobodyelsePosted on 2004-11-04 at 12:12:48ID: 12497674

>> I had no idea that they had things like CString back in those days.

I started with 16 Bit VC++ 1.3 and MFC 1.0 in 1993. The platform was Windows 3.11. The difference to Borland C++ was that VC++ had an integrated  'visual' Resource Editor - called ApStudio and MFC with Scribble Tutorial.. ODBC Access came with VC 1.4 in spring 1994 (CRecordset class and jet engine driver for Access 1.1). DOS applications could be compiled using a DOS-Extender (i forgot the name as i had no DOS past but came from VMS).

There was a Bit VC 1.1 (same time as 16 Bit 1.3) for Windows NT 3.5 (that had a Win 3.11 GUI).

Regards, Alex

 

by: itsmeandnobodyelsePosted on 2004-11-04 at 12:14:21ID: 12497689

>> There was a Bit VC 1.1

Seems i have to replace my keyboard. Should be "There was a 32 Bit VC 1.1".

 

by: rstaveleyPosted on 2004-11-04 at 13:04:45ID: 12498176

<Apologies for the continued trip down memory lane...>

DOS extenders like Phar Lap were only needed to extend the capabilities of DOS to break through the 640K barrier. I did pitifully little Windows 3.x stuff with Borland's OWL (Object Windows Library). Borland didn't seem to license much off Microsoft... possibly only the resource compiler. But most of my development at that time was text mode, compiled with a 1989 copy of Turbo C 1.0. which could fit onto a bootable 720K floppy with enough space for pkzip and a text editor but which wasn't to be trusted with floating point.

<Returning to the current decade... and the thread>

I think you're right about getline or perhaps an insufficient number of commas in an errant record making npos == string::npos, which isn't tested for. It certainly isn't a DOS thing :-)

 

by: w100ktnPosted on 2004-11-04 at 20:07:10ID: 12501167

Yeah, Alex, it works with that very small change. Thanks so much for your help.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...