You are currently offline, waiting for your internet to reconnect

How to read from and write to a text file by using Visual C++ .NET or Visual C++ 2005

For a Microsoft Visual C# .NET version of this article, see 816149.

For a Microsoft Visual Basic .NET version of this article, see 315828.

IN THIS TASK

SUMMARY
This step-by-step article describes how to read from and write to a text file by using Visual C++ .NET or Visual C++ 2005.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you must have:
  • Microsoft Visual C++ .NET or Microsoft Visual C++ 2005
This article assumes that you are familiar with the following topic:
  • Microsoft Visual C++ .NET or Visual C++ 2005
back to the top

Read and Write Text Files

The Write a Text File (Example 1) and Write a Text File (Example 2) sections describe how to use the StreamWriter class to write text to a file. The Read a Text File section of this article describes how to use the StreamReader class to read a text file.

back to the top

Write a Text File (Example 1)

The following code uses the StreamWriter class to open, to write, and to close the text file. In a similar way to the StreamReader class, you can pass the path name of a text file to the StreamWriter constructor to open the file automatically. The WriteLine method writes a complete line of text to the text file.
  1. Start Visual Studio .NET or Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.

    In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

    Note In Visual Studio 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates.
  4. In the Name text box, type Sample1, and then click OK.
  5. Open the Sample1.cpp file. Add the following code:
    using namespace System::IO;
  6. Replace the existing code of the Main function with the following code:
        try     {	    //Pass the file path and file name to the StreamWriter Constructor.	    StreamWriter* sw = new StreamWriter(S"C:\\Test.txt");	    //Write a line of text.	    sw->WriteLine(S"Hello World!!");	    //Write a second line of text.	    sw->WriteLine("From the StreamWriter class");	    //Close the file.	    sw->Close();    }    catch(Exception* e)    {        Console::WriteLine("Exception: {0}",e->Message);    }    __finally     {        Console::WriteLine("Executing finally block.");    }	    return 0;
  7. On the Debug menu, click Start to compile and run the application. This code creates a file that is named Test.txt on drive C. Open the Test.txt file in a text editor such as Notepad. The Test.txt file contains the following two lines of text:
    Hello World!!From the StreamWriter class
back to the top

Write a Text File (Example 2)

The following code uses the StreamWriter class to open, to write, and to close the text file. Unlike the previous example, this code passes two additional parameters to the constructor. The first parameter is the file path and the file name of the file. The second parameter, True, specifies that the file is opened in append mode. If you specify False for the second parameter, the contents of the file are overwritten each time you run the code. The third parameter specifies Unicode. Therefore, the StreamWriter class encodes the file in Unicode format. You can also specify the following encoding methods for the third parameter:
  • ASC11
  • Unicode
  • UTF7
  • UTF8
The Write method is similar to the WriteLine method, except that the Write method does not automatically embed a carriage return or line feed (CR/LF) character combination. This is useful when you want to write one character at a time.
  1. Start Visual Studio .NET or Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.

    In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

    Note In Visual Studio 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates.
  4. In the Name text box, type Sample3, and then click OK.
  5. Open the Sample3.cpp file. Add the following code:
    using namespace System::IO;using namespace System::Text;
  6. Replace the existing code of the Main function with the following code :
        Int64 x;    try     {	    //Open the File.        StreamWriter* sw = new StreamWriter(S"C:\\Test1.txt", true, Encoding::ASCII);	    //Write out the numbers 0 to 9 on the same line.	    for(x=0; x < 10; x++)	    {		    sw->Write(x);	    }	    //Close the file.	    sw->Close();    }    catch(Exception* e)    {        Console::WriteLine(S"Exception: {0}", e->Message);    }    __finally     {        Console::WriteLine(S"Executing finally block.");    }	    return 0;
  7. On the Debug menu, click Start to compile and run the application. This code creates a file that is named Test1.txt on drive C. Open the Test1.txt file in a text editor such as Notepad. The Test1.txt file contains the following single line of text:
    0123456789
back to the top

Read a Text File

The following code uses the StreamReader class to open, to read, and to close the text file. You can pass the path name of a text file to the StreamReader constructor to open the file automatically. The ReadLine method reads each line of text, and then increments the file pointer to the next line as it reads. When the ReadLine method reaches the end of the file, it returns a null reference.
  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.

    In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

    Note In Visual Studio 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates.
  4. In the Name text box, type Sample2, and then click OK.
  5. Open the Sample2.cpp file. Add the following code:
    using namespace System::IO;
  6. Replace the existing code of the main function with the following code:
        String* line;    try         {	        //Pass the file path and file name to the StreamReader constructor.	        StreamReader* sr = new StreamReader(S"C:\\test1.txt");	        //Read the first line of text.	        line = sr->ReadLine();	        //Continue to read until you reach end of file.	        while (line != NULL) 	        {		        //Write the lie to console window.                Console::WriteLine(line);		        //Read the next line.                line = sr->ReadLine();	        }	        //Close the file.	        sr->Close();            Console::ReadLine();        }        catch(Exception* e)        {            Console::WriteLine(S"Exception: {0}",e->Message);        }        __finally         {            Console::WriteLine(S"Executing finally block.");        }        return 0;
  7. On the Debug menu, click Start to compile and run the application. Press ENTER to close the Console window. The Console window displays the contents of the Test1.txt file.
back to the top

Complete Code Listing

Write a Text File (Version 1)

#include <tchar.h>#using <mscorlib.dll>using namespace System;using namespace System::IO;int _tmain(){    try     {	    //Pass the file path and file name to the StreamWriter Constructor.	    StreamWriter* sw = new StreamWriter(S"C:\\Test.txt");	    //Write a line of text.	    sw->WriteLine(S"Hello World!!");	    //Write a second line of text.	    sw->WriteLine("From the StreamWriter class");	    //Close the file	    sw->Close();    }    catch(Exception* e)    {        Console::WriteLine("Exception: {0}",e->Message);    }    __finally     {        Console::WriteLine("Executing finally block.");    }	    return 0;}
Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample.To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
  1. Click Project, and then click <ProjectName> Properties.

    Note <ProjectName> is a placeholder for the name of the project.
  2. Expand Configuration Properties, and then click General.
  3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.
For more information about the common language runtime support compiler option, visit the following Microsoft Web site:
/clr (Common Language Runtime Compilation)
http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

Write a Text File (Version 2)

#include <tchar.h>#using <mscorlib.dll>using namespace System;using namespace System::IO;using namespace System::Text;int _tmain(){    Int64 x;    try     {	    //Open the File.        StreamWriter* sw = new StreamWriter(S"C:\\Test1.txt", true, Encoding::ASCII);	    //Write out the numbers 0 to 9 on the same line.	    for(x=0; x < 10; x++)	    {		    sw->Write(x);	    }	    //Close the file.	    sw->Close();    }    catch(Exception* e)    {        Console::WriteLine(S"Exception: {0}", e->Message);    }    __finally     {        Console::WriteLine(S"Executing finally block.");    }	    return 0;}

Read a Text File

#include <tchar.h>#using <mscorlib.dll>using namespace System;using namespace System::IO;int _tmain(){    String* line;    try         {	        //Pass the file path and file name to the StreamReader constructor.	        StreamReader* sr = new StreamReader(S"C:\\test.txt");	        //Read the first line of text.	        line = sr->ReadLine();	        //Continue to read until you reach end of file.	        while (line != NULL) 	        {		        //Write the lie to console window.                Console::WriteLine(line);		        //Read the next line.                line = sr->ReadLine();	        }	        //Close the file.	        sr->Close();            Console::ReadLine();        }        catch(Exception* e)        {            Console::WriteLine(S"Exception: {0}",e->Message);        }        __finally         {            Console::WriteLine(S"Executing finally block.");        }        return 0;}
back to the top

Troubleshooting

For all file manipulations, it is good programming practice to wrap the code inside a try-catch-__finally block to handle errors and exceptions. Specifically, you may want to release handles to the file in the final block so that the file is not locked indefinitely. Some possible errors include a file that does not exist, or a file that is already in use.

back to the top
REFERENCES
For more information about the StreamReader and StreamWriter classes, visit the following Microsoft Developer Network (MSDN) Web sites:
back to the top
Properties

Article ID: 816148 - Last Review: 11/22/2007 08:17:35 - Revision: 3.5

  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET 2003 Standard Edition
  • Microsoft Visual C++ .NET 2002 Standard Edition
  • kbsample kbcode kbfileio kbhowtomaster KB816148
Feedback