このブログは、旧・はてなダイアリー「檜山正幸のキマイラ飼育記 メモ編」(http://d.hatena.ne.jp/m-hiyama-memo/)のデータを移行・保存したものであり、今後(2019年1月以降)更新の予定はありません。

今後の更新は、新しいブログ http://m-hiyama-memo.hatenablog.com/ で行います。

gccでWindows API

MinGWgccWindows.hを備えているので、

#include <Windows.h>

#pragma comment(lib, "shlwapi.lib")

とかできる。Win32 APIを呼ぶことができる。

PowerShellコマンドを真似たヤツ。

bool testPath(const string &path, bool container)
{
  if (container) {
    return (bool)PathIsDirectory(path.c_str());
  } else {
    return (bool)PathFileExists(path.c_str());
  }

}

bool copyItem (const string &from, const string &to){
  return (bool)CopyFile((LPCTSTR) from.c_str(), (LPCTSTR) to.c_str(), TRUE);
}

bool moveItem (const string &from, const string &to){
  return (bool)MoveFile((LPCTSTR) from.c_str(), (LPCTSTR) to.c_str());
}

bool removeItem (const string &path){
  return (bool)DeleteFile((LPCTSTR) path.c_str());
}

どっかで拾ったソース。コンパイルできた。

// 第1引数が結果となるファイルの名前、第2引数が末尾にアペンドするファイル
// 第1引数は新規ファイルでもよい、第2引数は既存でなくてはならない
int appendFile(const string &resulting, const string &tail)
{
  HANDLE hTail;
  HANDLE hResulting;
  DWORD  dwBytesRead, dwBytesWritten, dwPos;
  BYTE   buff[4096];

 hTail = CreateFile(TEXT(tail.c_str()), // open first file
            GENERIC_READ,             // open for reading
            0,                        // do not share
            NULL,                     // no security
            OPEN_EXISTING,            // existing file only
            FILE_ATTRIBUTE_NORMAL,    // normal file
            NULL);                    // no attr. template

  if (hTail == INVALID_HANDLE_VALUE)
  {
    //printf("Could not open file (first).\n");   // error message
     return -1;
  }

  // Open the existing file, or if the file does not exist,
  // create a new file.

  hResulting = CreateFile(TEXT(resulting.c_str()), // open second file
              FILE_APPEND_DATA,         // open for writing
              FILE_SHARE_READ,          // allow multiple readers
              NULL,                     // no security
              OPEN_ALWAYS,              // open or create
              FILE_ATTRIBUTE_NORMAL,    // normal file
              NULL);                    // no attr. template

  if (hResulting == INVALID_HANDLE_VALUE)
  {
    //printf("Could not open file (second).\n");  // error message
     return -2;
  }

  // Append the first file to the end of the second file.
  // Lock the second file to prevent another process from
  // accessing it while writing to it. Unlock the
  // file when writing is complete.

  while (ReadFile(hTail, buff, sizeof(buff), &dwBytesRead, NULL)
      && dwBytesRead > 0)
    {
    dwPos = SetFilePointer(hResulting, 0, NULL, FILE_END);
    LockFile(hResulting, dwPos, 0, dwBytesRead, 0);
    WriteFile(hResulting, buff, dwBytesRead, &dwBytesWritten, NULL);
    UnlockFile(hResulting, dwPos, 0, dwBytesRead, 0);
    }

  // Close both files.
  CloseHandle(hTail);
  CloseHandle(hResulting);
  return 0;
}