C++重定向命令行结果到文件

// MyProcess.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<windows.h>
#include<iostream>
#include<atlstr.h>

using std::string;
using std::cout;
using std::cin;
using std::endl;

void GetInfoOfDos(const string& strCmd,string& strOut)
{
    HANDLE hOutputRead = nullptr, hOutputWrite = nullptr;
    SECURITY_ATTRIBUTES sa;
    ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    if (FALSE == CreatePipe(&hOutputRead, &hOutputWrite, &sa, 0))
    {
        printf("create output pipe failed,Error_code:%d", GetLastError());
        return;
    }
    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(STARTUPINFOA);
    GetStartupInfo(&si);
    //si.hStdInput = hOutputRead;
    si.hStdOutput = hOutputWrite;
    si.hStdError = hOutputWrite;
    si.wShowWindow = SW_SHOW;//SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

    CString cstrCmd = (CA2W)strCmd.c_str();
    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
    if (FALSE == CreateProcess(NULL, (LPWSTR)cstrCmd.GetBuffer(),&sa, &sa,
        TRUE, 0, 
        NULL, NULL, &si, &pi))
    {
        printf("create process failed,Error_code:%d", GetLastError());
        CloseHandle(hOutputRead);
        CloseHandle(hOutputWrite);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return;
    }
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(hOutputWrite);
    DWORD dwRetVal = 0;
    if (GetExitCodeProcess(pi.hProcess, &dwRetVal) == 0) {
        printf("ERROR!! GetExitCodeProcess()=[0]. GetLastError()=[%d].\n", GetLastError());
    }
    else {
        printf("The command runs successfully with returns code: [%d].\n", dwRetVal);
    }
    const unsigned long MAX_BUFFER = 4096;
    char szBuffer[MAX_BUFFER] = { 0 };
    unsigned long dwSize;
    while (1)
    {
        ZeroMemory(szBuffer, MAX_BUFFER);
        if (NULL == ReadFile(hOutputRead, szBuffer, MAX_BUFFER - 1, &dwSize, NULL)
            || 0 == dwSize)
        {
            break;
        }
        strOut += string((char*)szBuffer);
        Sleep(3);
    }
    CloseHandle(hOutputRead);
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}

void AppendToFile(const string& strCmd, string&strOut)
{
    HANDLE hRead = nullptr, hWrite = nullptr;
    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
    DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_READ;
    /*
    OSVERSIONINFOA osVersion;
    ZeroMemory(&osVersion, sizeof(OSVERSIONINFOA));
    osVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
    if (GetVersionExA(&osVersion))
    {
        if (VER_PLATFORM_WIN32_NT == osVersion.dwPlatformId)
        {
            dwShareMode |= FILE_SHARE_DELETE;
        }
    }
    */

    hWrite = CreateFileA("test.txt", GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE == hWrite)
    {
        printf("Create open file handle failed,Error:%d\n", GetLastError());
        return;
    }
    hRead = CreateFileA("test.txt", GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
        &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE == hRead)
    {
        printf("Create read file handle failed,Error:%d\n", GetLastError());
        return;
    }
    STARTUPINFOA si;
    si.cb = sizeof(STARTUPINFOA);
    GetStartupInfoA(&si);
    si.hStdInput = hRead;
    si.hStdOutput = hWrite;
    si.hStdError = hWrite;
    si.wShowWindow = SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

    if (FALSE == CreateProcessA(NULL, (LPSTR)strCmd.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
    {

        printf("Create process failed,Error:%d", GetLastError());
        CloseHandle(hRead);
        CloseHandle(hWrite);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return;
    }
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(hWrite);
    unsigned long nSize = GetFileSize(hRead, NULL);
    char *pBuffer = new char[nSize + 1];
    ZeroMemory(pBuffer, nSize + 1);
    DWORD dwSize;
    while (1)
    {
        if (FALSE == ReadFile(hRead, pBuffer, nSize, &dwSize, 0)
            || 0 == dwSize)
        {
            break;
        }
        strOut += (string((char*)pBuffer));
    }
    CloseHandle(hRead);
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}

int main()
{
    string strCmd("ping 127.0.0.1");
    string strOut("");
    //AppendToFile(strCmd, strOut);
    GetInfoOfDos(strCmd, strOut);
    cout << strOut.c_str() << endl;
    system("pause");
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>