Question

CStdioFile::ReadString incorrectly reports EOF

Asked by: Nhl2k

I'm using Visual C++ 6.0
I found out about an issue with CStdioFile::ReadString reporting EOF incorrectly if the last line in a file is a multiple of 128 without a newline character following it. I read about it online a while back, but I can't find that page anymore. A workaround that I did when this came up was to change my while loop from
while(inFile.ReadString(inLine))
to
while(inFile.ReadString(inLine)||inLine != "")
as it appears it reports EOF incorrectly but still puts the data in the string variable passed.
The problem is I have about 500 of these while loops scattered across different programs and I don't want to change them all to that, not to mention the other variations of EOF checking I do.
Is anyone familiar with this issue? Is there some patch that I can install to fix this?

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
2009-04-03 at 14:11:42ID24293823
Tags

MFC

Topic

Windows MFC Programming

Participating Experts
2
Points
250
Comments
20

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. Trying to use EOF for CFile
    I'm trying to read a binary flat file using MFC's CFile class. The problem comes when trying to check for an end-of -file (EOF) when I'm doing a "while()" loop. CFile filePtr; filePtr.Open(InPath, CFile::modeRead, NULL); while( !eof(filePtr) ) { filePtr.Read( ....
  2. EOF
    What is the right way of using EOF function? I have the following code: Dim tstrOpen As TextStream Dim strFileName As String Const ForReading = 1, ForWriting = 2, ForAppending = 8 On Error GoTo Errorhandler strFileName = dlgFile.Filename Set mfsysObj...
  3. Set EOF
    How can I set EOF in the file open for binary ?
  4. EOF
    I am reading a file in binary and using Do While not EOF(1) line input bla bla loop I am getting an error saying input past eof I assume it is a vbcrlf or something but how do I avoid this. Using the same code on one textfile the code works fine but on this file it doesn't....

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: itsmeandnobodyelsePosted on 2009-04-04 at 05:36:57ID: 24067108

>>>> The problem is I have about 500 of these while loops scattered across different programs and I don't want to change them all to that
You could derive from CStdioFile and provide a fix of ReadString in that derived class. So you would need to replace CStdioFile by CMyStdioFile everywhere and include your class header in stdafx.h , it perhaps is the better solution.

>>>> Is there some patch that I can install to fix this?
I actually never heard of this bug (and I don't use CStdioFile myself for at least 10 years - but std::ifstream or std::ofstream) but if it wasn't fixed in one of the latest service packs of VC6 (which I assume you already have installed) it probably won't be fixed anymore as VC6 was released in 1998 and there are three major releases of VC compiler released later.  

 

by: DanRollinsPosted on 2009-04-04 at 15:51:53ID: 24069388

The article you mention is probably:
  FIX: ReadString Gives Wrong Result Reading Long Strings
   http://support.microsoft.com/kb/152319

But it refers to a "retired" issue, one that was fixed years ago.  You can single-step into the CStdIoFile:ReadString code and see if it matches the code in that article.  You can, as, itsme said, derive from StdioFile and override the ReadString function with one that does not have the bug.

 

by: Nhl2kPosted on 2009-04-04 at 19:12:42ID: 24069898

itsmeandnobodyelse,
I've thought about doing that, but it still requires modifying about 60 programs.

DanRollins,
I've read about that issue and that's not the problem. I actually did a debug way back when I found out about this issue and stepped into the ReadString code. Looking through the code I actually saw why it wasn't reporting EOF correctly.
I did a test program yesterday where I created a simple for loop that wrote a line of 1 byte to 1000 bytes into a file. For each iteration, I reopened the file and did a ReadString, checking the result returned. It would return EOF for every multiple of 128.

I realize that Microsoft probably won't release any updates, I was just hoping maybe I had missed one, like an update to MFC or something that would fix this. I have the code for my simple for loop attached. Maybe one of you could try running it and seeing if you get the same results I do? If not, I may try reinstalling visual studio with the latest service pack to make sure I'm not using something that's not updated correctly.

Thanks

void CEOFTestDlg::OnButton1() 
{
	CStdioFile file;
	CString strLine;
	for(int i=0;i<1000;i++)
	{
		file.Open("testfile.txt",CStdioFile::modeWrite|CStdioFile::modeCreate);
		CString writeLine('A',i);
		file.WriteString(writeLine);
		file.Close();
		file.Open("testfile.txt",CStdioFile::modeRead);
		if(!file.ReadString(strLine))
		{
			CString temp;
			temp.Format("%d",i);
			MessageBox(temp);
		}
		file.Close();
	}
	MessageBox("Done");
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

Select allOpen in new window

 

by: itsmeandnobodyelsePosted on 2009-04-05 at 07:32:35ID: 24071598

>>>>> but it still requires modifying about 60 programs.
In Visual  Studio later than VC6 there is a 'replace all in files' where it could be done in less than 10 minutes.

But even in VC6 I have done a similar job in less than one hour. You should ask yourself whether any other solution requires less ...

Another thought ... You said the error only would occur if a text file ends with a 128 byte text string.

I think, the chance to happen that is pretty low. If you have some influence on how these text files were created you might find ways to make the risks negligible. Or you write a little batch job which adds a linefeed to all text files not ending with a linefeed.

 

by: DanRollinsPosted on 2009-04-05 at 14:44:08ID: 24073101

OK I found something.

First, I can verify the bug.  It works exactly as you describe.  When the file length is an exact multiple of 128,  CStdioFile::ReadString(CString& rString) returns FALSE.  That would match with what the documentation says only in the case where the file length is 0.

It frankly amazes me that this bug has been in place for so long.  I can find nothing in MSDN about it,, except that old note that says a somewhat different problem was solved in the MFC42 DLL.

The correct data is returned (rString is populated).  So all that is wrong is the return value.  Here's what I found:

In the MFC source code that comes with Visual Studio 2008, the function is identical with one single exception.  The last line of the function is changed like so...

    ...
    // return lpszResult != NULL;
    return nLen != 0;
}

You probably can't assume that some later/fixed version of the MFC DLL is available on your target systems.  So that leaves you with doing what you have been doing:  (checking for "") or writing an alternative function like MyReadString( file,s)  that returns the correct Boolean value, or deriving from CStdioFile.  All three options require the source code changes that you hope to avoid.

Sorry, but that's my take on it.

 

by: itsmeandnobodyelsePosted on 2009-04-05 at 23:21:05ID: 24074706

>>>> Sorry, but that's my take on it.

That is great. It offers a further option, to correct the bug in MFC and build a new one.

 

by: DanRollinsPosted on 2009-04-06 at 01:21:10ID: 24075188

I corrected an MFC bug once by adding one of the MFC files to my own project.  In this case, perhaps you could copy just that one cpp file (FileTxt.cpp) into your own project directory.  Rename it, add it to the project, make that one-line change to the src code.   Now all StdioFile object functions will go to your own code.

I tried this and got a warning and an error.  Both went away when I commented out the

   IMPLEMENT_DYNAMIC(CStdioFile, CFile)

at the very end of the file.  I'm not savvy enough about this to know what sort of "ripple-effect" such a change could have on a large project.  However, I can say that when I did this on the simple test app, the 128-byte messageboxes stopped popping up (except for the 0-length file one).

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 04:35:13ID: 24076165

>>>> I corrected an MFC bug once by adding one of the MFC files to my own project.  

I did it once (maybe 15 years ago)  when I had a support contract with MS. I reported a bug in the recordset classes and they helped me to rebuild MFC (more precisely the static library of MFC). I am pretty sure that the  makefiles for rebuilding MFC are available with VC6 (or can be downloaded) and as there are no further service packs it hardly will get overridden by a further update.

 

by: Nhl2kPosted on 2009-04-06 at 07:04:08ID: 24077379

itsmeandnobodyelse,
Unfortunately my program requires importing data from other systems into our system. So I'm at the mercy of the files created by other companies which on at least 2 occasions, have had a multiple of 128 as the last line and caused my program to stop loading the data. I had to create a fix for their program and distribute it so they could import the file. Overall the percentage is low, but if it fails just once I'll have to deal with it.

DanRollins,
Thanks for trying out my code and confirming the bug. At least now I know it's not something messed up in my setup. And I'm also amazed that it seems this isn't documented anywhere and I tried all kinds of searches on google with nothing mentioning the problem. Either it happens so rarely that it was never reported, or sometimes the last lines of files are not being read and nobody has noticed!

I'm not sure which way I'm going to handle the issue, but at least I know I'm not missing something simple like a patch. Thanks again for the help.

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 08:59:24ID: 24078669

>>>> it happens so rarely that it was never reported
Most text files written programmatically will have a linefeed at end. I can't remember one of the thousands of text files I've created programmatically which would end without a linefeed.

With text files created in some editor it might be different though there were former IDE's (even of VC compiler) which were not able to properly resolve two include statements if the first header file wasn't proper ended with a linefeed. Though that was in the middle nineties I still was used to add linefeeds to my source files. Though of course I wouldn't expect other people to have the same experiences, I would nevertheless assume that exactly 128 characters (or a multiple) are really rare exceptions for a manually created text file either.

Do you know how your sample file was created?

Newer programs might not use CStdioFile but std::ifstream. And a loop like

   string line;
   vector<string> all;
   ifstream ifs("x.txt");
   while (getline(ifs, line))
       all.push_back(line);
   ifs.close();

hasn't any issues with missing linefeeds.

 

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 09:15:48ID: 24078858

Note, the makefiles to rebuild MFC in VC6 should be found in vc98\mfc\src.

 

by: Nhl2kPosted on 2009-04-06 at 09:25:19ID: 24078958

Is it dangerous to recompile that? Could that cause other problems?

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 10:20:55ID: 24079519

>>>> Is it dangerous to recompile that? Could that cause other problems?

Hmmm. I would do it at a copy of current system (and I actually have done it that way). But if you only make the (little) change Dan has found out, you surely can't produce more problems than that it doesn't work nevertheless.

The greater danger might be that the makefiles don't work or produce some errors because of an insufficient environment. But if you've properly saved all files from and below the installation directory of VC6 I rarely can think of any irreparable issues. I think you've a good chance that it works at the first attempt if you work at the original folders (not on the copy) and run the batch file before which establishes the command line environment (something like vcvars32.bat, I didn't remember the name exactly).

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 10:24:04ID: 24079552

>>>> I would do it at a copy of current system

No, as I told below, I did it on the original and the copy was for backup reasons only.

 

by: DanRollinsPosted on 2009-04-06 at 12:17:31ID: 24080753

I was actually decribing a way to do it without creating a new MFC DLL.

The technique is to create your own local copy of a particular MFC object (in this case, CStdioFile).  When done that way, the linker will use your object (call your code) rather than the one in the standard DLL -- an OBJ file links before a LIB file does.  For all other MFC objects, it will use the original.  

You need not make any change to the MFC DLL itself nor experience the frustration of trying to get the make file to work (if that is even possible).

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 13:52:04ID: 24081615

>>>> nor experience the frustration of trying to get the make file to work (if that is even possible).
I made good experiences with that. I don't think that makefiles supported with the sources of MFC only have the purpose to arising frustrations ...

>>>> The technique is to create your own local copy of a particular MFC object (in this case, CStdioFile).  
Hmmm.

>>>> tried this and got a warning and an error.  Both went away when I commented out the
>>>>   IMPLEMENT_DYNAMIC(CStdioFile, CFile)

Do you really think, those implications are better than rebuilding - a never further updated - MFC dll?

Sorry, if the make fails with unresolvable errors that what you described might be an option (or better a last resort before deriving from CStdioFile). But never as the first way.

FYI: if you provide own object code for a class and all their members you can persuade the linker to taking your implementation rather than the one provided by an import library. However, only freshly new compiled code will take your implementation while any code already compiled takes the default import library. So actually you were using both versions of the code what may have unknown impacts if there is any optimization or static data involved.  

The   IMPLEMENT_DYNAMIC(CStdioFile, CFile) is the MFC way to send messages and notifications first to CStdioFile class and then to CFile class if they were not already resolved by CStdioFile. If commenting that you actually were spoiling MFC message management.



 

by: DanRollinsPosted on 2009-04-06 at 14:22:21ID: 24081850

The problem with creating a custom version of the MCF DLL is that you must distribute it with your application program.  It's over one megabyte.  And some of your customers will not "get the memo" and suddenly you're in DLL Hell.   Also, you have a major problem when you want to upgrade to a later version of MFC.

Yes, there is some danger in commenting out the IMPLEMENT_DYNAMIC line.  But doing so should only affect the program that links to your version of the object.  The change (and potential ripple effect) is "contained" -- affecting only this one program.   Normal QA testing -- of your one program -- will flush out problems.  And they are easy to isolate.  If something goes wrong, remove that one file from the build and see if it stops going wrong.

 

by: Nhl2kPosted on 2009-04-06 at 14:25:33ID: 24081879

So how does MFC link? I usually use the default option when creating a project, which is for a shared dll. Does that mean it's using whatever version of this function is on the machine it's run on?

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 15:20:39ID: 24082241

>>>> I usually use the default option when creating a project, which is for a shared dll.

Dan is right. If you were considering to fix the bug you either need to distribute your dll with the application (which isn't so much a danger if you put it into the folder where the app resides) *or* you build a static library of the MFC dll and link against what lets the size of your app increase but is an absolute safe method where I only have positive experiences with (it surely avoids any dll hell).

 

by: itsmeandnobodyelsePosted on 2009-04-06 at 15:22:47ID: 24082261

>>>> you have a major problem when you want to upgrade to a later version of MFC.

No, you can't upgrade a VC6 application to a later version of MFC.

You only can upgrade VC6 to a later Version of VC (and MFC) where the bug is already fixed.

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...