Read text file problem (CStdio::ReadString())

I have created a function that reads a text file containing a list of 
servers. The code for this function is below but for some reason it doesn't 
retrieve any data from servers.pdd. My code below shows that ReadString() is 
returning 0. Any ideas?

void CServersDlg::GetServerList()
{
  TRY
  {
    CStdioFile f;
    CString s;
    CString output;
    if(f.Open("servers.pdd", CFile::modeRead | CFile::shareExclusive | 
CFile::typeText))
    {
      BOOL retval;
      while(retval = f.ReadString(s)) // retval = 0, so does no iterations
      {
        output += s; //never occurs
      }
      MessageBox(output); // THIS APPEARS BUT output = ""
      f.Close();
    }
    else
    {
      AfxMessageBox("File could not be opened.");
    }
  }
  CATCH (CFileException, pEx)
  {
    TCHAR szErr[2048];
    pEx->GetErrorMessage(szErr, 2048);
    char buf[256];
    sprintf ( buf, "CFileException (%d): %s", pEx->m_cause, szErr);
    AfxMessageBox ( buf );
  }
  CATCH_ALL (pEx)
  {
    TCHAR szErr[2048];
    pEx->GetErrorMessage(szErr, 2048);
    char buf[256];
    sprintf ( buf, "Exception");
    AfxMessageBox ( buf );
  }
  END_CATCH_ALL
}

====

Here is the source text file (servers.pdd):

Test Server 1|London|192.168.150.43|9081;
Localhost|Here|127.0.0.1|9081; 


0
11/24/2005 1:15:15 AM
vc.mfc 33608 articles. 0 followers. Follow

2 Replies
1268 Views

Similar Articles

[PageSpeed] 15

Hi Mike,

            I tested your code on a sample dialog application and it is
working fine for me. The problem could be somewhere else.

-- 
Cheers
Check Abdoul
------------------

"Mike" <mikestanworth@gmailNOSPAM.com> wrote in message
news:Du8hf.4253$0o2.3656@newsfe3-gui.ntli.net...
> I have created a function that reads a text file containing a list of
> servers. The code for this function is below but for some reason it
doesn't
> retrieve any data from servers.pdd. My code below shows that ReadString()
is
> returning 0. Any ideas?
>
> void CServersDlg::GetServerList()
> {
>   TRY
>   {
>     CStdioFile f;
>     CString s;
>     CString output;
>     if(f.Open("servers.pdd", CFile::modeRead | CFile::shareExclusive |
> CFile::typeText))
>     {
>       BOOL retval;
>       while(retval = f.ReadString(s)) // retval = 0, so does no iterations
>       {
>         output += s; //never occurs
>       }
>       MessageBox(output); // THIS APPEARS BUT output = ""
>       f.Close();
>     }
>     else
>     {
>       AfxMessageBox("File could not be opened.");
>     }
>   }
>   CATCH (CFileException, pEx)
>   {
>     TCHAR szErr[2048];
>     pEx->GetErrorMessage(szErr, 2048);
>     char buf[256];
>     sprintf ( buf, "CFileException (%d): %s", pEx->m_cause, szErr);
>     AfxMessageBox ( buf );
>   }
>   CATCH_ALL (pEx)
>   {
>     TCHAR szErr[2048];
>     pEx->GetErrorMessage(szErr, 2048);
>     char buf[256];
>     sprintf ( buf, "Exception");
>     AfxMessageBox ( buf );
>   }
>   END_CATCH_ALL
> }
>
> ====
>
> Here is the source text file (servers.pdd):
>
> Test Server 1|London|192.168.150.43|9081;
> Localhost|Here|127.0.0.1|9081;
>
>


0
CheckAbdoul
11/24/2005 1:26:43 AM
This presumes that the file is found in the current working directory.  Are you absolutely
positively sure that the file is actually there?  For example, you could be reading an
empty file, which is not the one you think you are reading.  You should always do a file
open using a complete path.

Note that strings should be enclosed in _T() so you are writing Unicode-aware code, a good
programming habit to develop.

Not sure why you introduce a gratuitous boolean variable, or put an assignment in a while
condition.  

More below...

On Thu, 24 Nov 2005 01:15:15 GMT, "Mike" <mikestanworth@gmailNOSPAM.com> wrote:

>I have created a function that reads a text file containing a list of 
>servers. The code for this function is below but for some reason it doesn't 
>retrieve any data from servers.pdd. My code below shows that ReadString() is 
>returning 0. Any ideas?
>
>void CServersDlg::GetServerList()
>{
>  TRY
>  {
>    CStdioFile f;
>    CString s;
>    CString output;
>    if(f.Open("servers.pdd", CFile::modeRead | CFile::shareExclusive | 
>CFile::typeText))
>    {
>      BOOL retval;
>      while(retval = f.ReadString(s)) // retval = 0, so does no iterations
>      {
>        output += s; //never occurs
>      }
>      MessageBox(output); // THIS APPEARS BUT output = ""
>      f.Close();
>    }
>    else
>    {
>      AfxMessageBox("File could not be opened.");
>    }
>  }
>  CATCH (CFileException, pEx)
>  {
>    TCHAR szErr[2048];
>    pEx->GetErrorMessage(szErr, 2048);
>    char buf[256];
>    sprintf ( buf, "CFileException (%d): %s", pEx->m_cause, szErr);
****
Never use sprintf.  Assume that its usage is a deep and fundamental design error.
CString::Format would have been the correct approach.  For example, you have a 2048 byte
buffer for the error message, which you then reformat into a 256-byte buffer!  This makes
no sense at all!  Coding like this is why applications have buffer overflow exploits
possible; avoid all such forms of coding.
****
>    AfxMessageBox ( buf );
>  }
>  CATCH_ALL (pEx)
>  {
>    TCHAR szErr[2048];
>    pEx->GetErrorMessage(szErr, 2048);
>    char buf[256];
>    sprintf ( buf, "Exception");
>    AfxMessageBox ( buf );
****
There are many simpler ways of doing this, e.g.,
	CString s = _T("Exception");
	AfxMessageBox(s);
would be a good approach.  Using sprintf is a mistake for the reasons cited above; using
it to format a literal string is sillly.  Microsoft's failure to provide a GetErrorMessage
of the form GetErrorMessage(CString & s, PUINT HelpContext = NULL); is irresponsible. They
are saying "we WANT you to create code that doesn't work!")  I reported this years ago,
but hey, they were too busy doing IMPORTANT things like destroying the VS IDE to be
bothered to do something that would actually matter...
****
>  }
>  END_CATCH_ALL
>}
>
>====
>
>Here is the source text file (servers.pdd):
>
>Test Server 1|London|192.168.150.43|9081;
>Localhost|Here|127.0.0.1|9081; 
>
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15972)
11/24/2005 4:25:28 AM
Reply:

Similar Artilces:

"Error accesing file. Network connection may have been lost."
Hello everyone, How can I clear this message that I am getting everytime that I try to compile. "Error accesing file. Network connection may have been lost." Thanks in advance, JM JM, if you are not actually connecting to databases over the network, and you are using an older (unpatched) version of Access 2000, you may have run into this nasty bug: Error Message: Error Accessing File. Network Connection May Have Been Lost at: http://allenbrowne.com/ser-23a.html -- Allen Browne - Microsoft MVP. Perth, Western Australia Tips for Access users - http://allenbrowne.co...

wrapping text around another text box
My problem is this...I have two text boxes. I want to wrap one text box around the other text box but nothing seems to be working. What I want to do with the one to the left is make it into an "L" shape so that the box on the right simply fits in the empty space of the "L" to form basically a square. I have tried turning on all those text wrapping features with both boxes and cannot figure out for the life of me what is happening. I have a box drawn around the box on the right...don't know if that has something to do with it. I have tried removing it and sti...

Reading .wks file
Greetings...according to the Excel "help" file, as well as the file extension listing, I *should* be able to read an *.wks file, but Excel insists that it cannot. I am pretty sure the file was created in Microsoft Works. Is there a converter somewhere that I can download/install? Cheers - S2 Excel can read Works 2.0, not later. You have to save them in Works as excel files or Works 2.0 or get a commercial converter. -- Regards, Peo Sjoblom "Skip Stocks" <anonymous@discussions.microsoft.com> wrote in message news:AFC110E0-641D-4D87-9464-B930CC41CF02@microsoft....

Inserting text from a .txt file
I'm trying really hard to jump on the bandwagon and migrate from Outlook Express to Outlook, but the more I try, the more frustrated I get. Anyway, here is my question: How do I insert the text from a text file into my e-mail document. I am using the rtf editor. thank you, ~alan copy/paste? "~~Alan~~" <alan.shepro_NOSPAM@verizon.net> wrote in message news:%23%23AwZrIKEHA.1264@TK2MSFTNGP12.phx.gbl... > I'm trying really hard to jump on the bandwagon and migrate from Outlook > Express to Outlook, but the more I try, the more frustrated I get. > > Anywa...

problem with inventory items with lot numbers
Hello everybody, We have finished goods setup in Great Plains with track on lot numbers. That gives us the possibility to trace each lot and the system not allowed us to go to negatives. But we had a bad experience: if you pick an inventory item “ABC” that have 100 units available under lot number “123” and you want to make a negative variance of 10 units for this lot, after you fill the fields in “Item Transaction Entry” window, it is open “Item Lot Number Entry” window where you need to enter the lot information. Here you can pick the lot & type the quantity (middle of the screen...

Weird files
Just noticed I've got a ton of weird files with names like 2BE48300. The normal files seem to be ok. Any idea what might be producing all these extra files? -- For a list of all the ways technology has failed to improve the quality of life, please press three. ....Alice Kahn Not sure. Perhaps cleaning up your hard drive will help. http://www.officearticles.com/misc/how_to_clean_up_your_hard_drive.htm Are they Excel files? **************************** Hope it helps! Anne Troy www.OfficeArticles.com **************************** "Steve" <teu@qprc.inv> wrote in message...

"File access denied" to PST file
I have gone from Windows 2000 running Outlook 2000 to Windows XP Pro running Outlook 2003. When I try opening my saved .pst file in the new Outlook I get a message saying "File access denied. You do not have permission required to access to file mailbox.pst" I am logged on as Administrator, as I was on the old install. How do I open my saved mailbox.pst or archive.pst? TIA How did you try opening it? is this a local .pst file? If it is not on your C: drive, is it marked Read-Only? --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion int...

File won't open as read only
I have a file that is in use, but another person opens it and it doeasn't display the "file is in use" message. Is there a setting or fix? Hi have you shared this file? -- Regards Frank Kabel Frankfurt, Germany John wrote: > I have a file that is in use, but another person opens it > and it doeasn't display the "file is in use" message. Is > there a setting or fix? The file is on a network share. The share has all the appropriate permissions. >-----Original Message----- >Hi >have you shared this file? > >-- >Regards >Frank Ka...

path of .pst file
Hello everyone, I want to develop a stand alone application to send and recieve mails through MS Outlook.how can i retrieve the path of .pst file from .net application. actually i am thinking of reading the pst file of MS Outlook. is it possible? Thanks in Advance jyoti The pst file is stored in the profile path of the MSOUTLOK Since the path of the pst can be varied by the user, as can its name, ie it neednt be in the install default path, your app would first have to search for the pst, then you would have to figure out if it/which was the current pst. There are alleged to be third ...

Create Auto Text in Excel?
I want to be able to add the following function (=RIGHT(CELL("filename",A1),LEN(CELL("filename",A1))-FIND("]",CELL("filename ",A1),1))) into any excel sheet that I'm working on like you can do in Word with Auto Text insert. I think I should be able to do this with a macro but I can't figure out how to do it. Any help much appreciated. Cheers Lee First, you can shorten the formula a bit and reduce the number of function calls by using =MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,32) XL doesn&...

Outlook 2003 Send/Receive problems
I am running Outlook 2003 on Windows XP Pro. I have 2 email accounts set up. One is an Exchange 5.5 account. The other is a POP3 account. I have offline folders set up. I have set up the option to synchronize upon exiting. When I exit Outlook (while online), it goes through the Send/Receive dialog box, and there are no errors. But when I check my mail offline, new messages are not avaialable. I have made sure to check all folders that I want available offline. Even when manually hitting the Send/Receive button, it does the same thing. The only way I have been able to successfully syn...

Can't Convert Access 97 MDE File
I have an application that we have been unable to get to work on Access 2000. I have created an MDE file and used office developer tools to create a run time file for a machine with Access 2000 on it. I get the "You can't convert or enable an MDE file" when I go to run it. I know there is something you can change in the Office Developers Setup Wizard to get this to work, but I forgot what it was. Does anyone know. Thank You in Advance Tony No, you can't convert an MDE. You have to use Access 97 with the 97 MDE, and A2K MDE with Access 2000. (david) "Ton...

converting results from formula to text in a new column
I have a column that I have a formula in. I want to take the results of the formula and copy it into a new column so I can copy it as text. Thanks. There is a little trick: Say A1 has =1+1 first format B1 as Text second select A1 and do a copy third select B1 and paste/special as value B1 will contain 2 as a piece of text. -- Gary's Student "nodotdak" wrote: > I have a column that I have a formula in. I want to take the results of the > formula and copy it into a new column so I can copy it as text. Thanks. thanks. it worked. "Gary''s Stude...

scrambled excel file
Hi AGAIN. I'm trying to open a file that was deleted and later retrieved through GetData Back. It has an .xls extension, but when I try to open it, it's just symbols. Is there some way I can retrieve the proper info. from that file? Do I have to save it as something else? I really need this file back - l mean life & death!! I will attach the file to see if someone can figure this out for me. Thanks again for your help. Your advice last time was great. Sandy Attachment filename: wolf_info liz.xls Download attachment: http://www.excelforum.com/attachment.ph...

Make excel 2003 default to open files
I have Excel 2003 running alongside 2007. Double clicking an excel file causes it to open in 2007; how do I force 2003 to open the files instead? Sandy You most likely have to reset your file association from 2007 to 2003. Close Excel first and On the Windows Taskbar 1) Start>Run "excel.exe /unregserver"(no quotes)>OK. 2) Start>Run "excel.exe /regserver"(no quotes)>OK. See the space between exe and /regserver You might have to designate a full path to excel.exe for Office 2003 In that case Start>Run "C:\your path to\office11\excel.exe" ...

Word 2003, Select a block of text. How?
A word 2003 document where I want to select a 'block' of text in order to copy it in somewhere else. How do I mark such a 'block' ? -- ___________ Knut Willy I assume you know how to select text in general, so there are two possible interpretations of "block": 1. If you mean a large portion of text that requires scrolling the screen, click at one end of the desired selection, use the scroll bar to bring the other end in view, and Shift+click there. 2. If you mean a vertical column portion of a wider block of text, use Alt+drag to select i...

Read mail arn't marked as read anymore
After an SP upgrade of my Office 2000 the priviewed mail doesnt get marked as read anymore. I have tried to change the time (Tools->Options->Priview pane) from 2 -> 3 -> 4 seconds but nothing works. The only way to mark a mail as read is either to open it or right click it and chose Mark as read. Since I only use the priview pane this is very anoying for me. Is this a bug or has some setting changed with the SP? ...

How to give other users read-only access to Calendar
I want to allow the group Everyone to have read-only access to a calendar in a certain mailbox. I can do this by granting the permission 'Full mailbox access' (under 'Mailbox rights', under 'Exchange Advanced', for the particular user). However this also allows people to to do everything (ie: they become read-write users). I notice that every mailbox in the system has 'Read permissions' granted to group Everyone. This does not allow other people to open items in the mailbox, but as I understand it, permits Exchange Server and Outlook to do shared meetin...

Delete oldest file first
All, I am looking for some code that deletes the oldest files first in a directory. Any help would be great. Thanks in advance. "karibbean" <sharp_mind@REMOVE.this.email.msn.dotcom> wrote in message news:uJZArpxvFHA.2132@TK2MSFTNGP15.phx.gbl... > I am looking for some code that deletes the oldest files first in a > directory. Any help would be great. Thanks in advance. See FindFirstFile, FindNextFile, FindClose, DeleteFile -- With best wishes, Igor Tandetnik With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is ...

Series including text possible?
Is there a better way to create a "series" that is based on characters as well as digits than what I'm doing below? I created 3 columns. I put the text in one, the digits in the second that I could apply the series to, with the 3rd column holding a ":". But when I paste into the text file, I have tabs separating the 3 columsn where I was hoping for no space. So this here - NAQAHDAH 01 : NAQAHDAH 02 : NAQAHDAH 03 : should paste like this - NAQAHD6H01: NAQAHDAH02: NAQAHDAH03: NAQAHDAH04: NAQAHDAH05: NAQAHDAH06: NAQAHDAH07: NAQAHDAH08: NAQAHDAH09 Is there perhaps a w...

text running together
When I use a pulldown on a webpage, the text is not showing fully. It looks like the top word is running into the word below it. It looks like your trying to fit text into a too small space. Another example is when you look at a search box on a web page and the work "search" is already typed in it, it looks like the word "search" is showing the top half only. It's hard to explain. It takes a word such as microsoft and the bottom of the m and the i and the other letters are cut off. Also, when I try to print the page or if I try to print a document,...

View Pub 2002 files in home pub 2000
My wife did some work with Pub 2002 and we tried to view the files on our home computer that has home pub 2000. It did not recognize the .pub file extension. I tried to save the files as pub 2000 on her computer but still no good. The file extension that home pub 2000 recognize's .php , is there a way I can view these? Sorry - Home Publishing is not the same as Publisher. You could create a ..pdf file and view that. If you don't have Acrobat, you can download a free program from PrimoPDF (www.PrimoPDF.com). I will forewarn you, if you don't have broadband, it will take a while...

Label Wizard Problem #2
The Label format column is blank on on the label wizard and I am unable to continue. I have rebooted computer and program with no success. It sounds like the path to your labels folder is not correct. Check your setting in SOA, File - Configuration - Paths tab then lokk under labels. Make sure it points to the actual folder where your label formats reside. Marc "MKOTTO" <MKOTTO@discussions.microsoft.com> wrote in message news:5F8EE211-5B29-4846-9F49-0D3E30F5F2CE@microsoft.com... > The Label format column is blank on on the label wizard and I am unable to > contin...

Paste Special as Text
I have a small program that drops text from a Word table into Excel using Paste Special as Text. Although Paste Special as Text should insert the contents of the clipboard as text without any formatting this does not appear to be happening as it did with Excel 2000 . Excel 2003 splits the data when it meets a New Line or Carriage Return and drops anything after it down to row below. Any ideas what is causing this behaviour Thanks for your assistance Phil ...

scrolling text
is it possible to have scrolling text going across a spreadsheet like a screensaver until a button is pressed (or a short key)? please help thank you I thought that was a "given" with any mouse that had a wheel. Depress the wheel and see if you don't get a .four directional arrow icon. Move the mouse in the direction you wish to scroll. -- HTH, RD ============================================== Please keep all correspondence within the Group, so all may benefit! ============================================== "ash" <anonymous@discussions.microsoft.com> wrot...