0

我正在尝试从 VC++ 中的 textBox 写入文本文件,但文件中写入的数据不正确,而且每次都不同。

DWORD wmWritten;
textBox1->Text = "7.5";

array<Char>^ char_array1 = textBox1->Text->ToCharArray();

HANDLE hFile = CreateFile(L"C:\\MyData\\Performance\\info.txt", GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

BOOL bErrorFlag = WriteFile(hFile, &char_array1, (DWORD)(sizeof(char_array1)), &wmWritten, NULL);

结果:Œó-

怎么了?

4

1 回答 1

0

@Alex 说:

如果没有必要,不要混合托管和非托管类型

我完全同意。托管类是 .NET 类,由垃圾收集等处理。非托管类或本机类是传统的 C++ 类,您必须在其中管理所有内存。

在这种情况下,您可以使用托管代码完成所有操作。浏览有关如何输出到文件的 C# 网页,然后只需在 C++/CLI 中编写相应的代码。

例如,这里的链接:

https://msdn.microsoft.com/en-us/library/system.io.file(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-2

是我通过谷歌搜索“C# File IO”找到的。您可以单击此处的选项卡以查看 C# 或 C++ 中的代码片段(此处表示 C++ CLI)。基本上,你想要这个:

String^ path = "c:\\temp\\MyTest.txt";
if (  !File::Exists( path ) )
 {

   // Create a file to write to.
   StreamWriter^ sw = File::CreateText( path );
   try
   {
      //sw->WriteLine( "Hello" );
      //sw->WriteLine( "And" );
      //sw->WriteLine( "Welcome" );
      sw->Write(textBox1->Text);
   }
   finally
   {
      if ( sw )
               delete (IDisposable^)(sw);
   }
}
于 2015-02-06T16:05:08.603 回答