VC++获取控制台命令的输出结果

VC++获取控制台命令的输出结果

#include "stdafx.h"

#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;

BOOL ExecDosCmd(string cmd, string &output)
{
    SECURITY_ATTRIBUTES sa;
    HANDLE hRead, hWrite;

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;
    if (!CreatePipe(&hRead, &hWrite, &sa, 0))
    {
        return FALSE;
    }
    char command[1024]; // 长达1K的命令行,够用了吧
    strcpy(command, "Cmd.exe /C ");
    strcat(command, cmd.c_str());
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    si.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&si);
    si.hStdError = hWrite;  // 把创建进程的标准错误输出重定向到管道输入
    si.hStdOutput = hWrite; // 把创建进程的标准输出重定向到管道输入
    si.wShowWindow = SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    // 关键步骤,CreateProcess函数参数意义请查阅MSDN
    if (!CreateProcess(NULL, command, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
    {
        CloseHandle(hWrite);
        CloseHandle(hRead);
        return FALSE;
    }
    CloseHandle(hWrite);

    char buffer[4096] = {0}; // 用4K的空间来存储输出的内容,只要不是显示文件内容,一般情况下是够用了。
    DWORD bytesRead;
    while (true)
    {
        if (ReadFile(hRead, buffer, 4095, &bytesRead, NULL) == NULL)
            break;
        // buffer中就是执行的结果,可以保存到文本,也可以直接输出
        // AfxMessageBox(buffer);   //这里是弹出对话框显示
        // cout << "----:" << endl << buffer << endl;
    }
    CloseHandle(hRead);

    output = buffer;
    return TRUE;
}

int main()
{
    string output;
    ExecDosCmd("wmic diskdrive get Caption,SerialNumber", output);
    cout << output << endl;
    return 0;
}

C++获取windows系统分区大小及使用情况

C++使用Windows SDK获取系统分区大小以及使用情况,代码如下:

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"

#include <stdint.h>
#include <windows.h>
#include <iostream>
#include <string>

using namespace std;

void TestDrive()
{
    cout << "TestDrive" << endl;
    char* lpDrives = (char *)malloc(MAX_PATH * sizeof(char ));
    memset(lpDrives, 0, MAX_PATH * sizeof (char));

    DWORD dwLen = ::GetLogicalDriveStringsA(MAX_PATH, lpDrives);
    cout << "dwLen: " << dwLen << endl;

    DWORD driver_number = dwLen / 4;
    cout << "driver_number: " << driver_number << endl;

    string driver;
    LPTSTR start;
    for (DWORD nIndex = 0; nIndex < driver_number; nIndex++)
    {
        start = lpDrives + nIndex * 4;
        cout << "........................................." << endl;
        driver.append(start);
        cout << "lpDrives + nIndex * 4: " << lpDrives + nIndex * 4 << endl;
        cout << "DRIVE_REMOVABLE: " << DRIVE_REMOVABLE << endl;
        cout << "::GetDriveType(lpDrives + nIndex * 4): " << :: GetDriveType(lpDrives + nIndex * 4) << endl;
        if (::GetDriveType (start) == DRIVE_REMOVABLE)
        {
            driver.append(start);
            if (GetVolumeInformation (start, 0, 0, 0, 0, 0, 0, 0)) //判断驱动是否准备就绪
            {
                cout << "驱动准备就绪 " << endl;
            }
        }
        uint64_t lpFreeBytesAvailable = 0;
        uint64_t lpTotalNumberOfBytes = 0;
        uint64_t lpTotalNumberOfFreeBytes = 0;
        GetDiskFreeSpaceExA(lpDrives + nIndex * 4,
                            (PULARGE_INTEGER)&lpFreeBytesAvailable,
                            (PULARGE_INTEGER)&lpTotalNumberOfBytes,
                            (PULARGE_INTEGER)&lpTotalNumberOfFreeBytes);
        cout << "lpFreeBytesAvailable: " << lpFreeBytesAvailable << endl;
        cout << "lpTotalNumberOfBytes: " << lpTotalNumberOfBytes << endl;
        cout << "lpTotalNumberOfFreeBytes: " << lpTotalNumberOfFreeBytes << endl;
    }
    std::cout << "driver: " << driver << endl;
}

int main(int argc, char *argv[])
{
    TestDrive();
    return 0;
}

ubuntu安装libuv

ubuntu安装libuv

sudo apt-get install automake libtool curl
curl -sSL https://github.com/libuv/libuv/archive/v1.4.2.tar.gz | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.4.2sudo sh autogen.shsudo ./configure
sudo make 
sudo make installsudo rm -rf /usr/local/src/libuv-1.4.2 && cd ~/
sudo ldconfig

ado.net 连接mysql的类

ado.net 连接mysql的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace VideoSpider
{
    public class DBConn
    {
#if DEBUG
        private static   string _connectionString = @"server=61.164.149.180;User ID=sql_zuqiu;Password=FULFQcvuFsqnbQSL;database=zuqiu_bak;";
#else
        private static string _connectionString = @"server=localhost;User=11xs;Password=HPU3aMJVzECQfVXR;database=11xs";
#endif
        public static MySqlConnection OpenConnection( string connstr = "" )
        {

            if (connstr != "" )
            {
                _connectionString = connstr;
            }
            var conn = new MySqlConnection(_connectionString);
            conn.Open();
            return conn;
        }
    }
}

C#在线程中使用Invoke来调用UI线程里的控件

C#在线程中使用Invoke来调用UI线程里的控件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TextTool
{
    public partial class Form1 : Form
    {
        private Thread workThread = null; //工作线程
        private List <string> fileList = new List <string>();
        public Form1()
        {
            InitializeComponent();
        }

        // 导入 可多选
        private void button1_Click(object sender, EventArgs e)
        {
            Stream mystream;
            OpenFileDialog openfiledialog1 = new OpenFileDialog();
            openfiledialog1.Multiselect = true;//允许同时选择多个文件
            openfiledialog1.Filter = "txt files(*.txt)|*.txt|All files(*.*)|*.*" ;
            openfiledialog1.FilterIndex = 1;
            openfiledialog1.RestoreDirectory = true;
            if (openfiledialog1.ShowDialog() == DialogResult.OK)
            {
                if ((mystream = openfiledialog1.OpenFile()) != null)
                {
                    fileList.Clear();
                    for (int fi = 0; fi < openfiledialog1.FileNames.Length; fi++)
                    {
                        fileList.Add(openfiledialog1.FileNames[fi]);
                    }
                    mystream.Close();
                }

                listView1.Items.Clear();
                foreach (var filePath in fileList)
                {
                    ListViewItem lvi = new ListViewItem(filePath);
                    listView1.Items.Add(lvi);
                }
            }
        }

        // 合并处理并输出
        private void button2_Click(object sender, EventArgs e)
        {
            if (fileList.Count == 0)
            {
                MessageBox.Show("请先添加要处理的文件" );
                return;
            }

            SaveFileDialog savefiledialog1 = new SaveFileDialog();
            savefiledialog1.Filter = "txt files(*.txt)|*.txt" ;
            if (savefiledialog1.ShowDialog() == DialogResult.OK)
            {
                button2.Text = "处理中..." ;
                button2.Enabled = false;

                workThread = new Thread (WorkThread);
                workThread.Start(savefiledialog1.FileName);
            }
        }

        private int MyCompareString(string x, string y)
        {
            int pos1 = x.IndexOf("(" );
            int pos2 = x.IndexOf(")" );
            int cnt1 = Convert .ToInt32(x.Substring(pos1 + 1, pos2-pos1 -1));

            pos1 = y.IndexOf( "(");
            pos2 = y.IndexOf( ")");
            int cnt2 = Convert .ToInt32(y.Substring(pos1 + 1, pos2 - pos1 - 1));
 
            if (cnt1 > cnt2)
            {
                return -1;
            }
            else if (cnt1< cnt2)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public void WorkThread(object savePath)
        {
            List<string > allLines = new List< string>();
            foreach (var filePath in fileList)
            {
                allLines.AddRange( File.ReadAllLines(filePath));
            }

            int totalCount = 0;
            List<string > outputList = new List< string>();
            foreach (var line in (from t in allLines where t.Trim() != "" select t).Distinct())
            {
                int count = (from c in allLines where c == line select c).Count();
                totalCount += count;
                outputList.Add( $"{line} ( {count})");
            }
            outputList.Sort(MyCompareString);
            outputList.Add( $"总数:{totalCount}" );
            File.WriteAllLines(savePath.ToString(), outputList);

            Invoke( new MethodInvoker (delegate ()
            {
                button2.Text = "合并处理输出" ;
                button2.Enabled = true;
                MessageBox.Show("处理完成!" );
            }));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (workThread != null && workThread.IsAlive)
            {
                workThread.Abort();
            }
        }
    }
}

如果是WPF程序,则在线程中像下面这样操作控件

this.Dispatcher.Invoke(new Action( delegate
{
    lblState.Content = "正在检测域名" + fullUrl;
}));

C#使用OleDB连接Access数据库

C#使用OleDB连接Access数据库的代码:

public class DbHelper
{
    static DbHelper()
    {
        connectionString = GetConnectionString();
    }

    private static string connectionString;

    private static string GetConnectionString()
    {
        return string.Format( "File Name={0}\\link.udl", Application .StartupPath);
    }


    public static DataTable ExecuteDataTable( string sql)
    {
        try
        {
            using ( OleDbDataAdapter da = new OleDbDataAdapter (sql, connectionString))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds.Tables[0];
            }
        }
        catch( Exception e)
        {
            MessageBox.Show(e.Message);
            return null;
        }

    }

    public static void ExecuteNonQuery( string sql)
    {
        using ( OleDbConnection conn = new OleDbConnection (connectionString))
        {
            try
            {
                conn.Open();

                OleDbCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            finally
            {
                if (conn.State == ConnectionState.Open) conn.Close();
            }
        }          
    }

}