CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 27 of 27

Thread: CFile

  1. #16
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,234

    Re: CFile

    Quote Originally Posted by Paul McKenzie
    Second, that is really a weird requirement. What is the name of the class that is giving you this homework? Unless it is a class called "Using MFC in a console app" or something similar, I don't understand why using CFile would be a requirement -- it is more of a hindrance IMO if all you have is a console app and all you need is to read a file.

    Regards,

    Paul McKenzie
    Indeed it's really weird to learn MFC...

    Regards,
    Ovidiu

    @to OP:
    First, the good AppWizard can help you to avoid a lot of headaches in making your console application using MFC. It's so kind and will put for you all required header includes, libraries, and basic framework.
    Here is how to call it:
    • Visual Studio 6.0
      1. Select "File/New..." menu item or press "Ctrl+N".
      2. In "New" dialog, select "Projects" tab and choose "Win32 Console Application" from the list.
      3. Type in "Project name" field (e.g. "ConsMFC"), then push "OK".
      4. In "Win32 Console Application - Step 1 of 1" choose "An application that supports MFC".
      5. Hit "Finish"
    • Visual Studio 2005
      1. Select "File/New/Project..." menu item or press "Ctrl+Shift+N".
      2. In "New Project" dialog select project type "Visual C++/Win32" and the template "Win32 Console Application".
      3. Type the project name (e.g. "ConsMFC"), then push "OK".
      4. In "Win32 Application Wizard" click on "Application Settings" (or push "Next" button).
      5. Check "Add common header files for: MFC".
      6. Hit "Finish"

    Next, I will make a little sample application, trying to help solving your "homework assignment".
    Last edited by ovidiucucu; February 18th, 2007 at 06:38 AM.
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  2. #17
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,234

    Re: CFile

    Here is the example
    Code:
    #include "stdafx.h"
    #include "ConsMFC.h"
    
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif
    
    CWinApp theApp;
    
    int _tmain()
    {
       // initialize MFC and print and error on failure (added by AppWizard).
       if(!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
       {
          _tprintf(_T("Fatal Error: MFC initialization failed\n"));
          return 1;
       }
    
       LPCTSTR pszFilter = _T("Text files (*.txt)|*.txt|All files(*.*)|*.*||");
    
       TRY
       {
          CFileDialog dlgOpen(TRUE, NULL, NULL, OFN_HIDEREADONLY, pszFilter);
          if(IDOK == dlgOpen.DoModal())
          {
             CStringArray arrLines;
             CString strFileRead = dlgOpen.GetPathName();
             // open the file to be read
             CStdioFile fileRead(strFileRead, CFile::modeRead);
             CString strLine;
             while(fileRead.ReadString(strLine))
             {
                // filters (just as an example)
                // only lines  which begins with 'A' or 'a'
                if(!strLine.IsEmpty() 
                   && !strLine.Left(1).CompareNoCase(_T("a")))
                {
                   arrLines.Add(strLine);
                }
             }
             fileRead.Close();
             CFileDialog dlgSave(FALSE, _T("txt"), strFileRead, 
                                             OFN_OVERWRITEPROMPT, pszFilter);
             if(IDOK == dlgSave.DoModal())
             {
                CString strFileWrite = dlgSave.GetPathName();
                // open the file for write
                CStdioFile fileSave(strFileWrite, 
                                         CFile::modeWrite|CFile::modeCreate);
                const int nSize = arrLines.GetSize();
                for(int nIndex = 0; nIndex < nSize; nIndex++)
                {
                   // add CR-LF then write the line
                   strLine.Format(_T("%s\r\n"), arrLines.GetAt(nIndex));
                   fileSave.WriteString(strLine);
                }
             }
          }
       }
       CATCH_ALL(e)
       {
          e->ReportError(); // shows if something goes wrong
       }
       END_CATCH_ALL
    
       return 0;
    }
    NOTES:
    • I have used CStdioFile instead of CFile to easier read/write line-by line from/into the text file. As long as CStdioFile is derived from CFile that does not conflict with your initial requirements.
    • I have used CFileDialog to select files to read and write just for an example. You can modify the code according to your needs, as for example getting the file names from command line arguments.
    • I have used TRY/CATCH MFC macros to handle the exceptions which can be thrown from CFile (CStdioFile) methods.
    • You can still replace my ugly MFC code with plain WinAPI (like somebody suggested above), but first be sure you have enough "Antinevralgic" pills available...
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  3. #18
    Join Date
    Apr 1999
    Posts
    27,449

    Re: CFile

    Quote Originally Posted by ovidiucucu
    Indeed it's really weird to learn MFC...
    If the course is MFC related, then that is one thing. However, if it is a generic C++ class where you're learning the language, that is another story altogether.

    That's why I asked the name of the course that is being taught. If it is a general C++ class, then you are usually taught streams if you are reading and writing files, not commanded to use MFC to do this.

    Regards,

    Paul McKenzie

  4. #19
    Join Date
    Apr 1999
    Posts
    27,449

    Re: CFile

    Quote Originally Posted by s|lent
    What is the actual way I can achieve this? I was trying to make a vector of strings where I would store each line read from the first file, but I do not know how to read line by line.
    There is a more or less generic way to do this using std::back_inserter and using std::copy.

    http://www.codeguru.com/forum/showthread.php?t=367219

    Regards,

    Paul McKenzie

  5. #20
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,234

    Re: CFile

    @to s|lent
    Here is another "simplified" example by using command line arguments. The code is a little bit tricky because uses as target file name the "standard" m_strPrinterName member of CCommandLineInfo. To make a more engineering work you can derive from CCommandLineInfo and override ParseParam virual function (adding your own command line arguments).
    Anyhow, if something else is unclear, please do not hesitate to ask me.
    Code:
    CWinApp theApp;
    
    int _tmain()
    {
       int nRet = 0;
       if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
       {
          _tprintf(_T("Fatal Error: MFC initialization failed\n"));
          nRet = 1;
       }
       else
       {
          
          CCommandLineInfo cmdLine; 
          theApp.ParseCommandLine(cmdLine);
          CString strSourceFile = cmdLine.m_strFileName;
          CString strTargetFile = cmdLine.m_strPrinterName;
          if(!strSourceFile.IsEmpty() && !strTargetFile.IsEmpty())
          {
             TRY
             {
                CStdioFile fileRead(strSourceFile, CFile::modeRead|CFile::typeText);
                CStdioFile fileWrite(strTargetFile, 
                   CFile::modeWrite|CFile::modeCreate|CFile::typeText);
                CString strLine;
                while(fileRead.ReadString(strLine))
                {
                   // ... filter here then write....
                   fileWrite.WriteString(strLine);
                }
                _tprintf(_T("Success\nSource file:\t%s\nTarget file:\t%s"),
                         strSourceFile, strTargetFile);
             }
             CATCH_ALL(e)
             {
                const int nMaxError = 128;
                CHAR pszError[nMaxError];
                e->GetErrorMessage(pszError, nMaxError);
                _tprintf(pszError);
                nRet = 2;
             }
             END_CATCH_ALL
          }
          else
          {
             _tprintf(_T("Use command line: %s.exe \"source file\"")
                _T(" /pt \"destination file\""),
                theApp.m_pszAppName);
             nRet = 3;
          }
       }
       return nRet;
    }
    @to Paul McKenzie
    Of course I do not recommend as a big deal the MFC for a console application as well as I do not recommend in a serious MFC application (and I think you already know that) excesively use (as an universal_cool_better_always_saving_us replacement) of command line programming stuff [] like STL.
    But as long as the OP requirement was "use CFile MFC stuff in a console app" I just answered how can it be done and not how would be better.
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  6. #21
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: CFile

    Maybe I am missing something, but I do not see the need to
    store into any kind of container.

    Just read line by line, break the line up into tokens, and write
    the tokens to the desired files.

  7. #22
    Join Date
    Jun 2004
    Location
    bucharest, ro
    Posts
    53

    Re: CFile

    thank you so much for all the replies.

    @ovidiucucu - thanks a lot. Looks a bit weird to me that code since I am a beginner but I'll just google word by word
    I will start digging into this immediately to try understand it.

    Quote Originally Posted by Philip Nicoletti
    Just read line by line, break the line up into tokens, and write
    the tokens to the desired files.
    That is exactly what I was trying to achieve, but got stuck at the "read line by line" step. I do know the function for tokens, and that is tokenize - so I was going to split the lines up in tokens after I was finding out how do I read a single line at a time.
    the doer alone learneth. (nietzsche)

  8. #23
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,234

    Re: CFile

    Quote Originally Posted by s|lent
    That is exactly what I was trying to achieve, but got stuck at the "read line by line" step. I do know the function for tokens, and that is tokenize - so I was going to split the lines up in tokens after I was finding out how do I read a single line at a time.
    Dragul meu,
    Cu tot riscul de a-mi sari altii in cap, iti scriu pe romaneste: vrei sa-ti rezolvi o problema sau ai chef de flame-uri?
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  9. #24
    Join Date
    Jun 2004
    Location
    bucharest, ro
    Posts
    53

    Re: CFile

    ...Right.
    I do not know where the idea that I want a flame, anyway thank you for the posts so far.

    All I posted was what I understood I needed to do.

    If I said something wrong, I apologize.
    the doer alone learneth. (nietzsche)

  10. #25
    Join Date
    Jun 2004
    Location
    bucharest, ro
    Posts
    53

    Re: CFile

    Ok.


    I have tried but all I could come up with is:

    Code:
    #include <afx.h>
    #include <vector>
    #include <iostream>
    //#include <string.h>
    using namespace std;
    
    
    void main()
    {
    CStdioFile sursaFile, destFile;
    sursaFile.Open(_T("c:\\test.txt"), CFile::modeRead);
    destFile.Open(_T("c:\\test3.txt"), CFile::modeCreate|CFile::modeWrite);
    CString line, field1;
    
    while(sursaFile.ReadString(line))
    {
      destFile.WriteString(field1);
      cout <<*field1;
    }
    
    
    int z;
    cin >>z;
    
    }
    (the cout was to make me see if anything Ive wrote had any sense at all, I wanted to see if it still showed some values).
    This will never work so I will end by thanking you all for your kind help.

    @ovidiucucu - thank you for the example you posted; I have tried to read that but it is far too advanced for my very limited understanding. in the end I had a nervous breakdown because these things are way too advanced so anyway thank you for all your help and for the work you have put into solving my assignment but I have yet to learn a lot until I can understand what is written there.

    you guys rock here keep up the good work and again I apologize for this thread which' responses I have failed to understand.
    the doer alone learneth. (nietzsche)

  11. #26
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: CFile

    1) If you use ReadString to read in a line of text, you need to
    tokenize the CString into fields (if you use standard ifstream
    to read in, it can automatically do this).

    2) old versions of VC++ do not define operator << for CString.
    cast to LPCTSTR

    Code:
    cout << (LPCTSTR)field1;       // non unicode
    wcout << (LPCTSTR)field1;    // unicode

  12. #27
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: CFile

    Code:
    CString line, field1;
    
    while(sursaFile.ReadString(line))
    {
      destFile.WriteString(field1);
      cout <<*field1;
    }
    This code does not initialize field1......
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured