To get a string pointer usable by fopen()
, you should use the marshal_as
template function.
You can obtain a const char *
thusly:
#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
std::string fileName = marshal_as<std::string>(openFileDialog1->FileName);
FILE * fichero = fopen(fileName.c_str(), "r");
if(fichero)
{
However, do you really want to convert the string to narrow characters, therefore losing wide-character compatibility? No, you don't. You should actually use _wfopen
, and marshal_as<std::wstring>
(to get a wchar_t
pointer) instead:
#include <wchar.h>
#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
std::wstring fileName = marshal_as<std::wstring>(openFileDialog1->FileName);
FILE * fichero = _wfopen(fileName.c_str(), L"r");
if(fichero)
{
This is the correct code you should be using.
Note: To actually get a non-const char*
, or if you only have Visual 2005, you should use Marshal::StringToHGlobalAnsi
or Marshal::StringToHGlobalUni
instead (don't forget the Marshal::FreeHGlobal
when you're done with it) and cast the IntPtr into a char*
/wchar_t*
(probably via its ToPointer
method).