Problem with file IO

This is a discussion on Problem with file IO within the C++ Programming forums, part of the General Programming Boards category; Hi, I am fairly new to C++. My problem is that my project won't compile ever since I've added very ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    13

    Problem with file IO

    Hi,

    I am fairly new to C++. My problem is that my project won't compile ever since I've added very simple code for file output.

    Code:
    #include "iostream.h"
    #include "fstream.h"
    ...
    ...
    ...
    ofstream outfile;
    char filename[] = "c:/example.txt";
    outfile.open(filename, ios::out);
    if (!outfile)
    	{
    	cerr << "Can't open output file " << filename << endl;
    	return;
    	}
    outfile << table << endl;
    outfile.close();
    return;
    Above is just a chunk of the cpp file. "table" is a CString object containing 280x320 temperature values. I have been able to display a portion of it using an AfxMessageBox function, but I want to save all the values to a file. I am using Visual Studio .NET 2003, and I read somewhere that .NET doesn't have all the necessary library files. That makes NO sense to me but either way, I got myself the header files "iostream.h" and "fstream.h" and added them to my project. I still get the same compiling errors as before, saying (summarized):
    error C2065: 'cerr' : undeclared identifier
    error C2065: 'endl' : undeclared identifier
    error C2065: 'ofstream' : undeclared identifier
    error C2065: 'out' : undeclared identifier
    error C2065: 'outfile' : undeclared identifier
    error C2146: syntax error : missing ';' before identifier 'outfile'
    error C2228: left of '.close' must have class/struct/union type
    type is ''unknown-type''
    error C2228: left of '.open' must have class/struct/union type
    type is ''unknown-type''
    error C2593: 'operator <<' is ambiguous
    error C2653: 'ios' : is not a class or namespace name
    error C3861: 'endl': identifier not found, even with argument-dependent lookup
    error C3861: 'outfile': identifier not found, even with argument-dependent lookup
    Does anyone know what I need to do to get it working? to get it to save "table" to a file"? Have I done something wrong? Thanks.

    Chunky

  2. #2
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    712
    You should use include <iostream> and using namespace std not "iostream.h"
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    >> I read somewhere that .NET doesn't have all the necessary library files.
    The VC++ 2003 compiler and later versions don't come with iostream.h and fstream.h because those are non-standard headers. They are old versions that were used before there were standards. You should be using <iostream> and <fstream> without the .h, and as Micko said you must indicate that you are using the std namespace. This is a common issue so a look at the FAQ or a search might provide more information.

    Also, whatever tutorial, book, or learning source you got the code from is probably pretty outdated. The C++ library has been standardized since 1998. Consider finding a more up-to-date reference.

  4. #4
    Registered User
    Join Date
    Aug 2006
    Posts
    13
    I tried it but there's no change. Thanks anyways Micko.

    Can it be the location of the header files? I saved them in the same folder as the other header files from the same project.

    Are there different versions of fstream and iostream? Can it be that I have a wrong ones? How can I tell that fstream and iostream do what I need?

    Thanks

  5. #5
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    wait, did you move the iostream headers from the default directory into your project folder? don't do that.

  6. #6
    Registered User
    Join Date
    Aug 2006
    Posts
    13
    Thanks Daved, I'll keep looking.

    wait, did you move the iostream headers from the default directory into your project folder? don't do that.
    Hi Indigo0086, that is where I originally saved them. I copied iostream.h and fstream.h from a coworkers VC++ and saved them in my project folder. I'm not sure which is the default folder, but I will try "Microsoft Visual Studio .NET 2003\Vc7\include". Thanks.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    Don't use iostream.h or fstream.h. Delete them from your hard drive. In your code, use #include <iostream> and #include <fstream> and add using namespace std;. If you still get errors, post those.

    BTW, don't delete the files called iostream and fstream in your compiler's include directory, I'm talking about getting rid of the iostream.h and fstream.h (with the '.h') that you copied from your co-worker's machine.

  8. #8
    Registered User
    Join Date
    Aug 2006
    Posts
    13
    Ok, iostream.h and fstream.h are unfindable on my hard drive. They're gone. The first 3 lines of my code are:
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std
    Nothing else has been changed. I'm still getting the same errors as before, except this time I'm abbreviating a little less.
    Code:
    error C2065: 'cerr' : undeclared identifier
    error C2065: 'endl' : undeclared identifier
    error C2065: 'ofstream' : undeclared identifier
    error C2065: 'out' : undeclared identifier
    error C2065: 'outfile' : undeclared identifier
    error C2146: syntax error : missing ';' before identifier 'outfile'
    error C2228: left of '.close' must have class/struct/union type
            type is ''unknown-type''
    error C2228: left of '.open' must have class/struct/union type
            type is ''unknown-type''
    error C2561: 'CFSWinView::ShowImage' : function must return a value
            c:\Documents and Settings\HP_Administrator\My Documents\Working Copies\Copy of FSWin\FSWinView.h(84) : see declaration of 'CFSWinView::ShowImage'
    error C2593: 'operator <<' is ambiguous
            c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\include\afxstr.h(154): could be 'CDumpContext &operator <<<char,StrTraitMFC_DLL<_CharType>>(CDumpContext &,const ATL::CStringT<BaseType,StringTraits> &)'
            with
            [
                _CharType=char,
                BaseType=char,
                StringTraits=StrTraitMFC_DLL<char>
            ]
            c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\include\afxstr.h(108): or       'CArchive &operator <<<char,StrTraitMFC_DLL<_CharType>>(CArchive &,const ATL::CStringT<BaseType,StringTraits> &)'
            with
            [
                _CharType=char,
                BaseType=char,
                StringTraits=StrTraitMFC_DLL<char>
            ]
            while trying to match the argument list '('unknown-type', CString)'
    error C2653: 'ios' : is not a class or namespace name
    error C3861: 'endl': identifier not found, even with argument-dependent lookup
    error C3861: 'outfile': identifier not found, even with argument-dependent lookup
    error C3861: 'outfile': identifier not found, even with argument-dependent lookup
    error C3861: 'outfile': identifier not found, even with argument-dependent lookup
    error C3861: 'outfile': identifier not found, even with argument-dependent lookup
    There's obviously something else going on here. Any ideas?

  9. #9
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    using namespace std;

  10. #10
    Registered User
    Join Date
    Aug 2006
    Posts
    13
    same

  11. #11
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Maybe there was an error when you installed your ide/compiler. Did you use an exe installer or just copied the files to your hd.

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    If it can't find iostream, it should give an error that it cannot find the include file. Since it didn't give that error, that means it found iostream just fine. Then, it doesn't recognize cerr, which is declared in iostream. That usually means that it isn't getting the namespace correct, but you said you have "using namespace std;" under the #include's so that shouldn't be a problem. It is very odd that the compiler would be able to find iostream and fstream but not find the stuff inside if you are using the namespace correctly.

    Is the cerr error the very first one on the list?

  13. #13
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    post the rest of the file, maybe there's more to it that's causing the error.

  14. #14
    Registered User
    Join Date
    Aug 2006
    Posts
    13
    Thanks again for taking the time to look my work.
    Is the cerr error the very first one on the list?
    Yes.


    I created a project using the following code (copied from an online tutorial) and it works fine, does exactly what it should.
    Code:
    // basic file operations
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () {
      ofstream myfile;
      myfile.open ("example.txt");
      myfile << "Writing this to a file.\n";
      myfile.close();
      return 0;
    }
    So I'm guessing my installation is fine and there must be something different about my code that's giving me problems.
    I copied a lot more of my code below. I copied the #includes and declarations exactly as they appear, a small section on debugging (don't understand, thought it could be relevant), and the portion of code that I'm working on. Using the "Visual C++.NET Bible", I added a different method of file i/o (METHOD1)for which my project compiles. But when I debug it, I get an assertion error in a file called afxole.inl at line 166. (Everything within the 2 "test//test//test" comments is code added by me, otherwise, it was part of the original program)

    Code:
    // FSWinView.cpp : implementation of the CFSWinView class
    //
    ///////////////////////
    //// TEST // TEST /////
    #include <iostream>///
    #include <fstream>///
    using namespace std;///
    //// TEST // TEST /////
    ///////////////////////
    #include "stdafx.h"
    #include "FSWin.h"
    
    #include "camera.h"
    #include "FSWinDoc.h"
    #include "FSWinView.h"
    #include "FPFDlg.h"
    #include "fpfimg.h"
    #include "AlarmSettings.h"
    #include ".\fswinview.h"
    ...
    ...
    ...
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif
    ...
    ...
    ...
    #ifdef _DEBUG
    void CFSWinView::AssertValid() const
    {
    	CFormView::AssertValid();
    }
    
    void CFSWinView::Dump(CDumpContext& dc) const
    {
    	CFormView::Dump(dc);
    }
    
    CFSWinDoc* CFSWinView::GetDocument() // non-debug version is inline
    {
    	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFSWinDoc)));
    	return (CFSWinDoc*)m_pDocument;
    }
    #endif //_DEBUG
    ...
    ...
    ...
    int CFSWinView::ShowImage(int nImageType) 
    {
    	VARIANT va = m_Camera.GetImage(nImageType);
    
    	// Check validity of returned image
    	VARTYPE vt = (nImageType < 2 ? VT_I2 : (nImageType < 4 ? VT_R4 : VT_UI1));
        if (va.vt == VT_I2) // Error
    	return (int)va.iVal;
    
    	if (va.vt != (VT_ARRAY | vt))
    		return -1;
    
    	COleSafeArray sa;
    	sa.Attach(va);
    //////////////////////////////////////////////////////////////////////
    ////// TEST /// TEST /// TEST /// TEST /// TEST /// TEST /// TEST ////////////////////////
    	// Display dimensions of the array stored in "sa".
    	long w, h;
    	CString s, msg, table;
    	s.Format(_T("Dimensions: %d\n"), sa.GetDim());
    	msg += s;
    	sa.GetUBound(1, &w);
    	sa.GetUBound(2, &h);
    	w++;
    	h++;
    	s.Format(_T("Width of array: %ld\n"), w);
    	msg += s;
    	s.Format(_T("Height of array: %ld\n"), h);
    	msg += s;
    	AfxMessageBox(msg);
    	
    	// Display contents of "sa" (array of Kelvin temperature values) in the CString object "table".
    	float HUGEP *a_image;
    	sa.AccessData((void HUGEP **)&a_image);
    	for (int x=0 ; x<10 ; x++) // x<10 should be x<w
    	{
    		for (int y=0 ; y<10 ; y++) // y<10 should be y<h
    		{
    			s.Format("%4.2f  ", a_image[w*x+y]);
    			table += s;
    		}
    		s.Format(_T("\n"));
    		table += s;
    	}
    ////////////////////// NEW STUFF /////////////////////// (I got this from the "Visual C++ .NET Bible)
    	// Display contents of "table" in a text file. (Method 1)
    	HANDLE hFile = ::CreateFile("example.txt",
    					GENERIC_READ,
    					FILE_SHARE_READ,
    					0,
    					OPEN_EXISTING,
    					FILE_ATTRIBUTE_NORMAL,
    			 		NULL);
    	HANDLE pFile; //pFile was not defined in the Bible's example, so I added this.
    	if (hFile)
    	{
    		CFile file(hFile);
    		if (file.Open("example.txt", CFile::modeWrite))
    		{
    			try
    			{
    				file.SeekToEnd(); // Go to end of file so as to not overwrite existing data.
    				file.Write(table, strlen(table));
    				file.Close();
    			}
    			catch(CFileException* pe)
    			{
    				pe->ReportError();
    				if (pFile)
    				{
    					delete pFile;
    				}
    			}
    		}
    	}
    
    ///////////////////// END OF NEW STUFF //////////////////////
    /*	// Display contents of "table" in a text file. (Method 2)
    	ofstream outfile;
    	char filename[] = "c:/example.txt";
    	outfile.open(filename, ios::out);
    	if (!outfile) // Test file open.
    	{
    		cerr << "Can't open output file " << filename << endl;
    		return;
    	}
    	outfile << table << endl;
    	outfile.close();
    */
    ///// TEST /// TEST /// TEST /// TEST /// TEST /// TEST /// TEST ////////////////////////
    //////////////////////////////////////////////////////////////////////
    	DisplayImage(nImageType, sa);
    	VariantClear(&va);
    	return 0;
    }

  15. #15
    Registered User
    Join Date
    Aug 2006
    Posts
    13
    Oh ya, and based on what you said Daved,
    That usually means that it isn't getting the namespace correct, but you said you have "using namespace std;" under the #include's so that shouldn't be a problem.
    , I wasn't sure if the using namespace std needed to be inserted in a particular location, so I tried many different ones (ie. just before the object that's giving me problems; at the very beginning; under the #includes), but got the same problem.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Problem reading file
    By coder_009 in forum C Programming
    Replies: 10
    Last Post: 01-15-2008, 12:22 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 09:46 AM
  5. Totally puzzling IO problem
    By Vorok in forum C++ Programming
    Replies: 5
    Last Post: 01-06-2003, 06:10 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21