WriteConsoleOutputCharacter访问冲突

时间:2014-01-27 14:34:49

标签: c++ cmd

我一直在尝试在cmd上执行命令,而我正在使用WriteConsoleOutputCharacter。我的代码如下:

int main( void )
{
    HANDLE hStdout;
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

    fun(hStdout,L"file1",L"file2");
    return 0;
}

void fun( HANDLE hConsole,wchar_t* str1,wchar_t* str2 )
{
   COORD coordScreen = { 0, 0 };    // home for the cursor 
   LPDWORD cCharsWritten=0;
   //LPDWORD cCharsWritten; that was originally
   CONSOLE_SCREEN_BUFFER_INFO csbi; 
   DWORD dwConSize;

   if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
   {
      return;
   }

   dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

   std::wstring ss;
   ss=std::wstring(L"cp ")+ str1+std::wstring(L" ")+str2;


   if( !WriteConsoleOutputCharacter( hConsole,        // Handle to console screen buffer 
                                ss.c_str(),     // Character to write to the buffer
                                dwConSize,       // Number of cells to write 
                                coordScreen,     // Coordinates of first cell 
                                cCharsWritten ))// Receive number of characters written
   {
      return;
   }



   if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
   {
      return;
   }


   if( !FillConsoleOutputAttribute( hConsole,         // Handle to console screen buffer 
                                csbi.wAttributes, // Character attributes to use
                                dwConSize,        // Number of cells to set attribute 
                                coordScreen,      // Coordinates of first cell 
                                cCharsWritten )) // Receive number of characters written
   {
      return;
   }

   SetConsoleCursorPosition( hConsole, coordScreen );
}

代码编译很好但是首先我得到一个错误,说我在没有初始化它的情况下使用cCharsWritten。所以我将它设置为0(LPDWORD cCharsWritten = 0;)。但后来我一直在

Unhandled exception at 0x772c5033 in CpProgrammatically.exe: 0xC0000005: Access violation reading location 0x00446000.

在具有WriteConsoleOutputCharacter调用的行上。 我已经尝试了几乎我能想象的任何东西,但我无法弄清楚。我使用cCharsWritten变量的方式有什么问题吗?ss是unicode字符串的实际问题吗?任何帮助都会非常感激

1 个答案:

答案 0 :(得分:2)

您传递的参数cCharsWritten是一个out参数,函数在调用时填充。您可能希望将指针传递给DWORD。你传递的是一个空指针。

将decleration更改为:

DWORD cCharsWritten = 0;

然后将其传递给&cCharsWritten函数,以便函数可以使用写入的字符数填充变量。

另外,请确保ss中的字符数等于dwConSize中的字符数。看起来你传入的字符串指针的长度可能不等于dwConSize。使用ss.length()代替。