Skip to content

Latest commit

 

History

History
51 lines (44 loc) · 1.82 KB

how-to-write-a-text-file-cpp-cli.md

File metadata and controls

51 lines (44 loc) · 1.82 KB
title ms.custom ms.date ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic dev_langs helpviewer_keywords ms.assetid caps.latest.revision author ms.author manager
How to: Write a Text File (C++/CLI) | Microsoft Docs
11/04/2016
cpp-windows
article
C++
files [C++], text
text files, writing in C++
39ecdba6-84e0-485c-a202-84cf6d7b8d4a
8
mikeblome
mblome
ghogen

How to: Write a Text File (C++/CLI)

The following code example demonstrates how to create a text file and write text to it using the xref:System.IO.StreamWriter class, which is defined in the xref:System.IO namespace. The xref:System.IO.StreamWriter constructor takes the name of the file to be created. If the file exists, it is overwritten (unless you pass True as the second xref:System.IO.StringWriter constructor argument).

The file is then filed using the xref:System.IO.StreamWriter.Write%2A and xref:System.IO.TextWriter.WriteLine%2A functions.

Example

// text_write.cpp  
// compile with: /clr  
using namespace System;  
using namespace System::IO;  
  
int main()   
{  
   String^ fileName = "textfile.txt";  
  
   StreamWriter^ sw = gcnew StreamWriter(fileName);  
   sw->WriteLine("A text file is born!");  
   sw->Write("You can use WriteLine");  
   sw->WriteLine("...or just Write");  
   sw->WriteLine("and do {0} output too.", "formatted");  
   sw->WriteLine("You can also send non-text objects:");  
   sw->WriteLine(DateTime::Now);  
   sw->Close();  
   Console::WriteLine("a new file ('{0}') has been written", fileName);  
  
   return 0;  
}  

See Also

File and Stream I-O
.NET Programming with C++/CLI (Visual C++)