エクセルのハイパーリンクを作るやつ
04/26 フォルダの中身をエクセルのハイパーリンクにするやつを作りました。
05/02 UNICODE対応にしたので記事を更新しました。
05/04 ログ機能強化とフォルダ構成の変更を行いました。
main.h
//---------------------------------------------------------------------------- /// @file main.h /// @brief エクセルハイパーリンクメーカーヘッダ /// @details エクセルハイパーリンクメーカーです。 //---------------------------------------------------------------------------- /// @mainpage エクセルハイパーリンクメーカー /// /// @section 概要 /// エクセルハイパーリンクを作成します。 /// /// @section history 履歴 /// - 2015/05/01 開発を開始しました。 /// - 2015/05/02 ワイド文字のファイル名が開けない問題が分かったのでワイド文字対応にしました。 /// - 2015/05/03 ログ出力を改良しました。 /// /// @version 0.2.1 /// @date 2015/05/03 /// @author Copyright (C) 2015 hidakas1961 All rights reserved. //---------------------------------------------------------------------------- #pragma once //---------------------------------------------------------------------------- // グローバル関数 //---------------------------------------------------------------------------- /// @brief ワイド文字メイン関数 /// @param [in] argc コマンドライン引数の個数 /// @param [in] argv コマンドライン引数の文字列配列 /// @return 終了コード /// @details ワイド文字(Unicode?)バージョンのメイン関数です。 int wmain( int argc, wchar_t * argv[] );
main.cpp
//---------------------------------------------------------------------------- /// @file main.cpp /// @brief エクセルハイパーリンクメーカー /// @details エクセルハイパーリンクメーカーです。 //---------------------------------------------------------------------------- #include "main.h" #include <TLogStream.h> #include <locale.h> #include <codecvt> #include <conio.h> //---------------------------------------------------------------------------- // 名前空間使用宣言 //---------------------------------------------------------------------------- using namespace std; using namespace Common; //---------------------------------------------------------------------------- // ローカル変数 //---------------------------------------------------------------------------- static const size_t maxpath = 1024; ///< フルパス最大文字数 static const size_t maxdepth = 100; ///< 最大ディレクトリ深さ static bool hidden = false; ///< 非表示ファイル許可フラグ static bool sysfile = false; ///< システムファイル許可フラグ static wofstream * pfout = 0; ///< ファイル出力ストリームポインタ static wostream * pout = 0; ///< 出力ストリームポインタ static size_t count = 0; ///< リンク数カウンタ static wchar_t root[ maxpath ]; ///< 入力ディレクトリ名 static bool nexts[ maxdepth ]; ///< 次ファイル有無フラグテーブル //---------------------------------------------------------------------------- // ローカル関数 //---------------------------------------------------------------------------- /// @brief ファイルスキップ判定関数 /// @param [in] data ファイル検索データ /// @return なし /// @details ファイルをスキップするか判定します。 static bool IsSkip( WIN32_FIND_DATAW & data ) { LogOut().Begin( __func__ ); LogOut().Hex ( "data ", data ); bool result = false; if ( ! wcscmp( data.cFileName, L"." ) || ! wcscmp( data.cFileName, L".." ) ) { result = true; } else if ( data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN ) { result = ! hidden; } else if ( data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM ) { result = ! sysfile; } LogOut().Data( "result", result ); LogOut().End ( __func__ ); return result; } /// @brief 属性情報出力関数 /// @param [in] path パス /// @param [in] pdata ファイル検索データポインタ /// @return なし /// @details 属性情報を出力します。 static void OutputAttributes( const wchar_t * path, WIN32_FIND_DATAW * pdata = 0 ) { LogOut().Begin( __func__ ); LogOut().Data ( "path", path ); // ファイル属性を取得します。 DWORD attr; if ( pdata ) { // ファイル検索データからファイル属性を取得します。 attr = pdata->dwFileAttributes; } else { // ファイルパスからファイル属性を取得します。 attr = GetFileAttributesW( path ); } if ( attr != static_cast< DWORD >( -1 ) ) { // ディレクトリでないか調べます。 if ( ! ( attr & FILE_ATTRIBUTE_DIRECTORY ) ) { // 拡張子を取得します。 wchar_t ext[ _MAX_EXT ]; _wsplitpath_s( path, 0, 0, 0, 0, 0, 0, ext, _MAX_EXT ); if ( ext[ 0 ] == L'.' ) { * pout << ( ext + 1 ); } else { * pout << L"なし"; } } } * pout << L"\t"; LogOut().End( __func__ ); } /// @brief インデント出力関数 /// @param [in] depth ディレクトリ深さ /// @return なし /// @details インデントを出力します。 static void OutputIndent( size_t depth ) { LogOut().Begin( __func__ ); LogOut().Data ( "depth", depth ); // ディレクトリ深さを巡回します。 for ( size_t i = 0; i < depth; i++ ) { // ディレクトリ深さを調べます。 if ( i == depth - 1 ) { // 次のファイル有無フラグを調べます。 if ( nexts[ i ] ) { * pout << L"├"; } else { * pout << L"└"; } } // 次のファイル有無フラグを調べます。 else if ( nexts[ i ] ) { * pout << L"│"; } * pout << L"\t"; } LogOut().End( __func__ ); } /// @brief ハイパーリンク式出力関数 /// @param [in] path パス /// @param [in] name 表示名 /// @return なし /// @details ハイパーリンク式を出力します。 static void OutputHyperLink( const wchar_t * path, const wchar_t * name ) { LogOut().Begin( __func__ ); LogOut().Data ( "path ", path ); LogOut().Data ( "name ", name ); LogOut().Data ( "count", count++ ); * pout << L"=HYPERLINK(\"" << path << L"\",\"" << name << L"\")" << endl; LogOut().End( __func__ ); } /// @brief ディレクトリ出力関数 /// @param [in] subdir サブディレクトリ /// @param [in] depth ディレクトリ深さ /// @return なし /// @details ディレクトリを出力します。 static void OutputDirectory( const wchar_t * subdir = 0, size_t depth = 0 ) { LogOut().Begin( __func__ ); LogOut().Data ( "subdir", subdir ); LogOut().Data ( "depth ", depth ); // 開始ディレクトリをコピーします。 wchar_t path[ maxpath ]; wcscpy_s( path, root ); size_t len = wcslen( path ); if ( path[ len - 1 ] != '\\' ) { wcscat_s( path, L"\\" ); len++; } // サブディレクトリを追加します。 size_t len2 = len; if ( subdir ) { wcscat_s( path, subdir ); len2 = wcslen( path ); if ( path[ len2 - 1 ] != '\\' ) { wcscat_s( path, L"\\" ); len2++; } } // ワイルドカードを追加します。 wcscat_s( path, L"*.*" ); // ファイルを検索します。 WIN32_FIND_DATAW data, next; HANDLE handle = FindFirstFileW( path, & data ); if ( handle != INVALID_HANDLE_VALUE ) { // 先頭ファイルを検索します。 bool result; while ( ( result = FindNextFileW( handle, & data ) != FALSE ) && IsSkip( data ) ); // 検索ファイルを巡回します。 for ( ; result; data = next ) { // 次のファイルを検索します。 while ( ( result = FindNextFileW( handle, & next ) != FALSE ) && IsSkip( next ) ); // 次のファイル有無テーブルを設定します。 nexts[ depth ] = result; // パスを作成します。 path[ len2 ] = '\0'; wcscat_s( path, data.cFileName ); // 属性情報を出力します。 OutputAttributes( path, & data ); // インデントを出力します。 OutputIndent( depth + 1 ); // ハイパーリンク式を出力します。 OutputHyperLink( path, data.cFileName ); // サブディレクトリでかつリパースポイントでないか調べます。 if ( ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) && ! ( data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT ) ) { // サブディレクトリを出力します。 OutputDirectory( path + len, depth + 1 ); } } FindClose( handle ); } LogOut().End( __func__ ); } //---------------------------------------------------------------------------- // グローバル関数 //---------------------------------------------------------------------------- // ワイド文字メイン関数 int wmain( int argc, wchar_t * argv[] ) { #ifdef _LOGFILE // ログファイルを作成します。 CreateLog( _LOGFILE ); #endif // _LOGFILE LogOut().Begin( __func__ ); // ロケールを設定します。 setlocale( LC_ALL, "Japanese" ); // タイトルを表示します。 LogOut().Line ( "≪エクセルハイパーリンクメーカー≫" ); cout << "≪エクセルハイパーリンクメーカー≫" << endl << endl; bool error = false; ///< エラーフラグ const wchar_t * dirname = 0; ///< ディレクトリ名 const wchar_t * outfile = 0; ///< 出力ファイル名 // コマンドライン引数を巡回します。 for ( int i = 1; i < argc; i++ ) { // オプションスイッチか調べます。 if ( argv[ i ][ 0 ] == '-' ) { // オプションスイッチの種類を調べます。 if ( ! wcscmp( argv[ i ] + 1, L"o" ) ) { // 出力ファイル名を設定します。 if ( ! outfile ) { if ( i + 1 < argc && argv[ i + 1 ][ 0 ] != '-' ) { outfile = argv[ ++i ]; } else { error = true; cout << endl << "出力ファイル名がありません。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else { error = true; cout << endl << "出力パスオプションが重複しています。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else if ( ! wcscmp( argv[ i ] + 1, L"hidden" ) ) { // 非表示ファイル許可フラグをセットします。 if ( ! hidden ) { hidden = true; wcout << L"\"" << argv[ i ] << L"\" : 非表示ファイル許可" << endl; } else { error = true; cout << endl << "非表示ファイル許可オプションが重複しています。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else if ( ! wcscmp( argv[ i ] + 1, L"system" ) ) { // システムファイル許可フラグをセットします。 if ( ! sysfile ) { sysfile = true; wcout << L"\"" << argv[ i ] << L"\" : システムファイル許可" << endl; } else { error = true; cout << endl << "システムファイル許可オプションが重複しています。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else { error = true; cout << endl << "不明なオプションです。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } // ディレクトリ名を調べます。 else if ( ! dirname ) { // ディレクトリ名を設定します。 dirname = argv[ i ]; } else { error = true; cout << endl << "余分な引数です。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } // エラーフラグを調べます。 while ( ! error ) { // ディレクトリ名を調べます。 if ( ! dirname ) { // カレントディレクトリを設定します。 dirname = L"."; } // 入力ディレクトリ名のフルパスを取得します。 if ( GetFullPathNameW( dirname, maxpath, root, 0 ) ) { wcout << L"入力ディレクトリ : \"" << root << L"\"" << endl; // 入力ディレクトリが存在するか調べます。 DWORD attr = GetFileAttributesW( root ); if ( attr != static_cast< DWORD >( -1 ) ) { // ディレクトリか調べます。 if ( attr & FILE_ATTRIBUTE_DIRECTORY ) { // 出力ファイル名を調べます。 if ( outfile ) { // フルパスを取得します。 wchar_t path[ maxpath ]; if ( GetFullPathNameW( outfile, maxpath, path, 0 ) ) { wcout << L"出力ファイル名 : \"" << path << L"\"" << endl; // 出力パスがディレクトリ名でないか調べます。 DWORD attr = GetFileAttributesW( path ); if ( attr != static_cast< DWORD >( -1 ) ) { if ( attr & FILE_ATTRIBUTE_DIRECTORY ) { error = true; cout << endl << "出力ファイル名はディレクトリです。" << endl; break; } } // ファイル出力ストリームを作成します。 pfout = new wofstream( path, ios::binary ); // 出力モードを設定します。 pfout->imbue( locale( locale(""), new codecvt_utf16< wchar_t, 0x10ffff, static_cast< codecvt_mode >( generate_header | little_endian ) >() ) ); // 出力ストリームポインタを設定します。 pout = pfout; } else { error = true; cout << endl << "不正なファイル名です。" << endl; break; } } else { // 出力ストリームポインタを設定します。 pout = & wcout; } } else { error = true; cout << endl << "ディレクトリではありません。" << endl; break; } } else { error = true; cout << endl << "入力ディレクトリが存在しません。" << endl; break; } } else { error = true; cout << endl << "不正なディレクトリ名です。" << endl; break; } // タイトル行を出力します。 * pout << L"拡張子\tパス" << endl; // 開始ディレクトリの属性情報を出力します。 OutputAttributes( root ); // 開始ディレクトリのインデントを出力します。 OutputIndent( 0 ); // 開始ディレクトリのハイパーリンクを出力します。 OutputHyperLink( root, root ); // サブディレクトリを出力します。 OutputDirectory(); // 出力ストリームを削除します。 if ( pfout ) { pfout->close(); delete pfout; } cout << endl << "正常に終了しました。" << endl; break; } #ifdef _DEBUG // キー入力を要求します。 cout << endl << "何か押してください。" << endl; _getch(); #endif // _DEBUG LogOut().End( __func__ ); return 0; }
ソースコード
以下のプロジェクトをソリューションに追加してビルドしてください。
開発環境は Windows Vista VC++ 2010 Express です。
共通ライブラリ
Excelハイパーリンクメーカー
以上です。
VC++のフィルター設定とかめんどくさいので
04/25 補助用のツールを作りました。
05/02 UNICODE 対応にしました。
05/04 ログ機能強化とフォルダ構成の変更を行いました。
main.h
//---------------------------------------------------------------------------- /// @file main.h /// @brief VCプロジェクトファイルメーカーヘッダ /// @details VCプロジェクトファイルメーカーです。 //---------------------------------------------------------------------------- /// @mainpage VCプロジェクトファイルメーカー /// /// @section 概要 /// VCプロジェクトファイルを作成します。 /// /// @section history 履歴 /// - 2015/05/01 開発を開始しました。 /// - 2015/05/02 ワイド文字のファイル名が開けない問題が分かったのでワイド文字対応にしました。 /// - 2015/05/03 ログ出力を改良しました。 /// /// @version 0.2.1 /// @date 2015/05/03 /// @author Copyright (C) 2015 hidakas1961 All rights reserved. //---------------------------------------------------------------------------- #pragma once //---------------------------------------------------------------------------- // グローバル関数 //---------------------------------------------------------------------------- /// @brief ワイド文字メイン関数 /// @param [in] argc コマンドライン引数の個数 /// @param [in] argv コマンドライン引数の文字列配列 /// @return 終了コード /// @details ワイド文字(Unicode?)バージョンのメイン関数です。 int wmain( int argc, wchar_t * argv[] );
main.cpp
//---------------------------------------------------------------------------- /// @file main.cpp /// @brief VCプロジェクトファイルメーカー /// @details VCプロジェクトファイルメーカーです。 //---------------------------------------------------------------------------- #include "main.h" #include <TLogStream.h> #include <locale.h> #include <codecvt> #include <conio.h> //---------------------------------------------------------------------------- // 名前空間使用宣言 //---------------------------------------------------------------------------- using namespace std; using namespace Common; //---------------------------------------------------------------------------- // ローカル変数 //---------------------------------------------------------------------------- /// アイテムグループ出力タイプ enum enumItemType { ITEM_FILTER, ///< フィルターファイル用のフィルターアイテムグループ ITEM_FILTER_FILE, ///< フィルターファイル用のファイルアイテムグループ ITEM_PROJECT_FILE, ///< プロジェクトファイル用のファイルアイテムグループ }; static const size_t maxpath = 1024; ///< フルパス最大文字数 static const size_t maxdepth = 100; ///< 最大ディレクトリ深さ static bool hidden = false; ///< 非表示ファイル許可フラグ static bool sysfile = false; ///< システムファイル許可フラグ static wofstream * pfout = 0; ///< ファイル出力ストリームポインタ static wostream * pout = 0; ///< 出力ストリームポインタ static size_t count = 0; ///< リンク数カウンタ static wchar_t root[ maxpath ]; ///< 入力ディレクトリ名 static bool nexts[ maxdepth ]; ///< 次ファイル有無フラグテーブル //---------------------------------------------------------------------------- // ローカル関数 //---------------------------------------------------------------------------- /// @brief ファイルスキップ判定関数 /// @param [in] data ファイル検索データ /// @return なし /// @details ファイルをスキップするか判定します。 static bool IsSkip( WIN32_FIND_DATAW & data ) { LogOut().Begin( __func__ ); LogOut().Hex ( "data ", data ); bool result = false; if ( ! wcscmp( data.cFileName, L"." ) || ! wcscmp( data.cFileName, L".." ) ) { result = true; } else if ( data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN ) { result = ! hidden; } else if ( data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM ) { result = ! sysfile; } LogOut().Data( "result", result ); LogOut().End ( __func__ ); return result; } /// @brief ディレクトリ出力関数 /// @param [in] item アイテムタイプ /// @param [in] subdir サブディレクトリ /// @param [in] depth ディレクトリ深さ /// @return なし /// @details ディレクトリを出力します。 static void OutputDirectory( int item, const wchar_t * subdir = 0, size_t depth = 0 ) { LogOut().Begin( __func__ ); LogOut().Data ( "item ", item ); LogOut().Data ( "subdir", subdir ); LogOut().Data ( "depth ", depth ); // 開始ディレクトリをコピーします。 wchar_t path[ maxpath ]; wcscpy_s( path, root ); size_t len = wcslen( path ); if ( path[ len - 1 ] != '\\' ) { wcscat_s( path, L"\\" ); len++; } // サブディレクトリを追加します。 size_t len2 = len; if ( subdir ) { wcscat_s( path, subdir ); len2 = wcslen( path ); if ( path[ len2 - 1 ] != '\\' ) { wcscat_s( path, L"\\" ); len2++; } } // ワイルドカードを追加します。 wcscat_s( path, L"*.*" ); // ファイルを検索します。 WIN32_FIND_DATAW data, next; HANDLE handle = FindFirstFileW( path, & data ); if ( handle != INVALID_HANDLE_VALUE ) { // 先頭ファイルを検索します。 bool result; while ( ( result = FindNextFileW( handle, & data ) != FALSE ) && IsSkip( data ) ); // 検索ファイルを巡回します。 for ( ; result; data = next ) { // 次のファイルを検索します。 while ( ( result = FindNextFileW( handle, & next ) != FALSE ) && IsSkip( next ) ); // 次のファイル有無テーブルを設定します。 nexts[ depth ] = result; // パスを作成します。 path[ len2 ] = '\0'; wcscat_s( path, data.cFileName ); // アイテムの種類を調べます。 if ( item == ITEM_FILTER ) { if ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { * pout << L" <Filter Include=\"" << ( path + len ) << L"\" />" << endl; } } else if ( item == ITEM_FILTER_FILE ) { if ( ! ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) { if ( subdir ) { * pout << L" <None Include=\"" << ( path + len ) << L"\">" << endl; * pout << L" <Filter>" << subdir << L"</Filter>" << endl; * pout << L" </None>" << endl; } else { * pout << L" <None Include=\"" << ( path + len ) << L"\" />" << endl; } } } else if ( item == ITEM_PROJECT_FILE ) { if ( ! ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) { * pout << L" <None Include=\"" << ( path + len ) << L"\" />" << endl; } } // サブディレクトリでかつリパースポイントでないか調べます。 if ( ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) && ! ( data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT ) ) { // サブディレクトリを出力します。 OutputDirectory( item, path + len, depth + 1 ); } } FindClose( handle ); } LogOut().End( __func__ ); } //---------------------------------------------------------------------------- // グローバル関数 //---------------------------------------------------------------------------- // ワイド文字メイン関数 int wmain( int argc, wchar_t * argv[] ) { #ifdef _LOGFILE // ログファイルを作成します。 CreateLog( _LOGFILE ); #endif // _LOGFILE LogOut().Begin( __func__ ); // ロケールを設定します。 setlocale( LC_ALL, "Japanese" ); // タイトルを表示します。 LogOut().Line ( "≪VCプロジェクトファイルメーカー≫" ); cout << "≪VCプロジェクトファイルメーカー≫" << endl << endl; bool error = false; ///< エラーフラグ const wchar_t * dirname = 0; ///< ディレクトリ名 const wchar_t * outfile = 0; ///< 出力ファイル名 // コマンドライン引数を巡回します。 for ( int i = 1; i < argc; i++ ) { // オプションスイッチか調べます。 if ( argv[ i ][ 0 ] == '-' ) { // オプションスイッチの種類を調べます。 if ( ! wcscmp( argv[ i ] + 1, L"o" ) ) { // 出力ファイル名を設定します。 if ( ! outfile ) { if ( i + 1 < argc && argv[ i + 1 ][ 0 ] != '-' ) { outfile = argv[ ++i ]; } else { error = true; cout << endl << "出力ファイル名がありません。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else { error = true; cout << endl << "出力パスオプションが重複しています。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else if ( ! wcscmp( argv[ i ] + 1, L"hidden" ) ) { // 非表示ファイル許可フラグをセットします。 if ( ! hidden ) { hidden = true; wcout << L"\"" << argv[ i ] << L"\" : 非表示ファイル許可" << endl; } else { error = true; cout << endl << "非表示ファイル許可オプションが重複しています。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else if ( ! wcscmp( argv[ i ] + 1, L"system" ) ) { // システムファイル許可フラグをセットします。 if ( ! sysfile ) { sysfile = true; wcout << L"\"" << argv[ i ] << L"\" : システムファイル許可" << endl; } else { error = true; cout << endl << "システムファイル許可オプションが重複しています。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } else { error = true; cout << endl << "不明なオプションです。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } // ディレクトリ名を調べます。 else if ( ! dirname ) { // ディレクトリ名を設定します。 dirname = argv[ i ]; } else { error = true; cout << endl << "余分な引数です。" << endl; wcout << L"\"" << argv[ i ] << L"\"" << endl; break; } } // エラーフラグを調べます。 while ( ! error ) { // ディレクトリ名を調べます。 if ( ! dirname ) { // カレントディレクトリを設定します。 dirname = L"."; } // 入力ディレクトリ名のフルパスを取得します。 if ( GetFullPathNameW( dirname, maxpath, root, 0 ) ) { wcout << L"入力ディレクトリ : \"" << root << L"\"" << endl; // 入力ディレクトリが存在するか調べます。 DWORD attr = GetFileAttributesW( root ); if ( attr != static_cast< DWORD >( -1 ) ) { // ディレクトリか調べます。 if ( attr & FILE_ATTRIBUTE_DIRECTORY ) { // 出力ファイル名を調べます。 if ( outfile ) { // フルパスを取得します。 wchar_t path[ maxpath ]; if ( GetFullPathNameW( outfile, maxpath, path, 0 ) ) { wcout << L"出力ファイル名 : \"" << path << L"\"" << endl; // 出力パスがディレクトリ名でないか調べます。 DWORD attr = GetFileAttributesW( path ); if ( attr != static_cast< DWORD >( -1 ) ) { if ( attr & FILE_ATTRIBUTE_DIRECTORY ) { error = true; cout << endl << "出力ファイル名はディレクトリです。" << endl; break; } } // ファイル出力ストリームを作成します。 pfout = new wofstream( path, ios::binary ); // 出力モードを設定します。 pfout->imbue( locale( locale(""), new codecvt_utf16< wchar_t, 0x10ffff, static_cast< codecvt_mode >( generate_header | little_endian ) >() ) ); // 出力ストリームポインタを設定します。 pout = pfout; } else { error = true; cout << endl << "不正なファイル名です。" << endl; break; } } else { // 出力ストリームポインタを設定します。 pout = & wcout; } } else { error = true; cout << endl << "ディレクトリではありません。" << endl; break; } } else { error = true; cout << endl << "入力ディレクトリが存在しません。" << endl; break; } } else { error = true; cout << endl << "不正なディレクトリ名です。" << endl; break; } // フィルターファイル用のテキストを出力します。 * pout << L"以下のテキストを \"~.vcxproj.filters\" にコピーしてください。" << endl; * pout << L"~ここから~" << endl; * pout << L"<?xml version=\"1.0\" encoding=\"utf-8\"?>" << endl; * pout << L"<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">" << endl; * pout << L" <ItemGroup>" << endl; // フィルターグループを出力します。 OutputDirectory( ITEM_FILTER ); * pout << L" </ItemGroup>" << endl; // ファイルグループを出力します。 * pout << L" <ItemGroup>" << endl; OutputDirectory( ITEM_FILTER_FILE ); * pout << L" </ItemGroup>" << endl; * pout << L"</Project>" << endl; * pout << L"~ここまで~" << endl; // プロジェクトファイル用のテキストを出力します。 * pout << endl << L"以下のテキストを \"~.vcxproj\" の適当な場所に挿入してください。" << endl; * pout << L"~ここから~" << endl; * pout << L" <ItemGroup>" << endl; // ファイルグループを出力します。 OutputDirectory( ITEM_PROJECT_FILE ); * pout << L" </ItemGroup>" << endl; * pout << L"~ここまで~" << endl; // 出力ストリームを削除します。 if ( pfout ) { pfout->close(); delete pfout; } cout << endl << "正常に終了しました。" << endl; break; } #ifdef _DEBUG // キー入力を要求します。 cout << endl << "何か押してください。" << endl; _getch(); #endif // _DEBUG LogOut().End( __func__ ); return 0; }
ソースコード
以下のプロジェクトをソリューションに追加してビルドしてください。
開発環境は Windows Vista VC++ 2010 Express です。
共通ライブラリ
VCプロジェクトファイルメーカー
以上です。
エクセルのハイパーリンクのJPGファイルをIE以外で開くには?
エクセル用のハイパーリンク作成ツールを作っていて気がついたのですが、
何故だかハイパーリンクのJPGファイルを開こうとすると、
JPGファイルの既定のプログラムの設定を無視して、
超大っ嫌いなIEが立ち上がってしまうんですよね。
せっかくデフォルトのブラウザをクロームに設定しているっつぅのに。(--〆)
そこでグーグル先生でいろいろ調べたんだけど、
ハイパーリンクのファイルの関連付けは単純には変えられないらしくて、
結局レジストリをいじることになりました。
解決策はレジストリエディタで
\HKEY_CLASSES_ROOT\.jpg
を丸ごと削除することでした。
削除するのは怖いので名前を変えてみたのですが、
ちゃんとハイパーリンクでJPGの既定のプログラムが立ち上がるようになりました。
おしまい。
DLLとストリームのサンプルプログラム
DLLにしてみるテスト
いつもよく使う関数やマクロを共通ライブラリにしようと思って、
どうせならDLLの練習を兼ねてDLLにしてみました。
家で使っているのはVC++ 2010 Expressなんですが、
こいつは2012 Expressなどと違って空のソリューションが作れない仕様になっているのね。
だから最初に何らかのプロジェクトも一緒に作ってやる必要があるんですよね。
ところが新規でプロジェクトを作るときってのは、
最初にプロジェクト名を聞いてきて、デフォルトではソリューション名も同じにされちゃうんですよね。
それでわざわざソリューション名のところで別の名前を入力する必要があるわけなんです。
で、CommonというDLLプロジェクトを最初に作って、
次にSampleというアプリケーションプロジェクトを追加したわけなんですが、
何もない空っぽのDLLプロジェクトをビルドしようとすると、Common.libが無いとか言って怒られるんですよね。
本当は無くても動くんだけど、しょうがないのでDllMain()を追加しました。
Common.h
//---------------------------------------------------------------------------- /// @file Common.h /// @brief 共通ライブラリモジュールヘッダ /// @details すべてに共通のライブラリです。 //---------------------------------------------------------------------------- #pragma once #include <windows.h> //---------------------------------------------------------------------------- // マクロ定義 //---------------------------------------------------------------------------- #ifdef COMMON_EXPORTS #define COMMON_API __declspec(dllexport) ///< DLL宣言マクロ #else // COMMON_EXPORTS #define COMMON_API __declspec(dllimport) ///< DLL宣言マクロ #endif // COMMON_EXPORTS #ifndef __func__ #define __func__ __FUNCTION__ ///< 関数名事前定義マクロ #endif // __func__ /// @brief トークン文字列取得マクロ /// @details トークンを文字列として取得します。 #define STRING( token ) #token /// @brief マクロトークン文字列取得マクロ /// @details マクロを展開して得られたトークンを文字列として取得します。 #define MACRO_STRING( macro ) STRING( macro ) //---------------------------------------------------------------------------- // グローバル関数 //---------------------------------------------------------------------------- /// @brief DLLメイン関数 /// @param [in] hModule モジュールハンドル /// @param [in] ul_reason_for_call 関数を呼び出す理由 /// @param [in] lpReserved 予約済み /// @retval TRUE 成功 /// @retval FALSE 失敗 /// @details DLLモジュールのエントリーポイントです。 COMMON_API BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ); //---------------------------------------------------------------------------- /// @brief 共通ライブラリ名前空間 /// @details 共通ライブラリ名前空間です。 //---------------------------------------------------------------------------- namespace Common {}
Common.cpp
//---------------------------------------------------------------------------- /// @file Common.cpp /// @brief 共通ライブラリモジュール //---------------------------------------------------------------------------- #include "Common.h" // DLLメイン関数 BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch ( ul_reason_for_call ) { case DLL_PROCESS_ATTACH : // ここでDLLの初期化処理を行います。 break; case DLL_THREAD_ATTACH : case DLL_THREAD_DETACH : break; case DLL_PROCESS_DETACH : // ここでDLLの終了処理を行います。 break; } return TRUE; }
サンプルプロジェクトのほうは、デバッグコンソールにストリームでログを出力するだけのものです。
main.h
//---------------------------------------------------------------------------- /// @file main.h /// @brief メインモジュールヘッダ /// @details メインモジュールです。 //---------------------------------------------------------------------------- #pragma once //---------------------------------------------------------------------------- // グローバル関数 //---------------------------------------------------------------------------- /// @brief メイン関数 /// @return なし /// @details メイン関数です。 extern void main(); /// @brief テスト関数 /// @param [in] param 引数 /// @return 戻り値 /// @details テスト用の関数です。 extern int func( int param );
main.cpp
//---------------------------------------------------------------------------- /// @file main.cpp /// @brief メインモジュール /// @details メインモジュールです。 //---------------------------------------------------------------------------- /// @mainpage コンソールサンプルプログラム /// /// @section summary 概要 /// コンソールアプリケーションのサンプルプログラムです。 /// /// @section history 履歴 /// - 2015/04/04 開発を開始しました。 /// - 2015/04/05 まだ開発中です。 /// /// @version 1.0.0 /// @date 2015/04/05 /// @author Copyright (C) 2015 hidakas1961 All rights reserved. //---------------------------------------------------------------------------- #include "main.h" #include <TDebugOut.h> #include <TLogOut.h> #include <conio.h> //---------------------------------------------------------------------------- // 名前空間使用宣言 //---------------------------------------------------------------------------- using namespace std; using namespace Common; //---------------------------------------------------------------------------- // ローカル変数 //---------------------------------------------------------------------------- static TDebugOut debugout; ///< デバッグ出力ストリーム static TLogOut logout( debugout ); ///< ログ出力ストリーム //---------------------------------------------------------------------------- // グローバル関数 //---------------------------------------------------------------------------- // メイン関数 void main() { // 共通DLLはプロジェクト設定のほうでロード済みなので(やっても良いみたいですが)不要です。 // LoadLibraryA( "Common" ); logout << "サンプルプログラムです。" << endl; logout << __FILE__ << ":" << __LINE__ << endl << endl; logout.Begin( __func__ ); int result = func( 123 ); logout.DataValue( "func()", result ); logout.End( __func__ ); cout << endl << "何か押してください。" << endl; _getch(); } // テスト関数 int func( int param ) { logout.Begin( __func__ ); int result = -param; logout.DataValue( "result", result ); logout.End( __func__ ); return result; }
うちのパソコンはCPUがセレロンでOSがビスタという超しょぼいノートパソコンなので、
C++の標準ライブラリを使おうとすると、信じられないくらい遅くなって精神的に良くないので、
今まで避けて通ってきたのですが、仕事でC++を使うことになって止むなく標準ライブラリに着手しました。
今まで画面出力関係はすべてprintf()でまかなってきたのですが、やはりcoutとかいうストリーム使うと、
いちいちcharとTCHARで関数を使い分ける必要もなくて、超便利なことに気が付いてしまいました。
そこでまずはログ出力用の出力ストリームクラスを作ってみました。
TLogOut.h
//---------------------------------------------------------------------------- /// @file TLogOut.h /// @brief ログ出力クラスヘッダ /// @details ログ出力クラスです。 //---------------------------------------------------------------------------- #pragma once #include "Common.h" #include <iostream> #include <fstream> #include <stdio.h> #include <stdarg.h> //---------------------------------------------------------------------------- // 共通ライブラリ名前空間 //---------------------------------------------------------------------------- namespace Common { //------------------------------------------------------------------------ /// @brief ログ出力クラス /// @details ログ出力クラスです。 //------------------------------------------------------------------------ class TLogOut { //-------------------------------------------------------------------- // 定数 //-------------------------------------------------------------------- private : static const int m_defIndent = 2; ///< デフォルトインデント数 //-------------------------------------------------------------------- // 動的変数 //-------------------------------------------------------------------- private : std::ofstream * m_ofs; ///< ファイル出力ストリームポインタ std::ostream * m_out; ///< 出力ストリームポインタ int m_indent; ///< インデント数 int m_block; ///< ブロック数 const char * m_header; ///< ヘッダー文字列 //-------------------------------------------------------------------- // 構築子と解体子 //-------------------------------------------------------------------- public : /// @brief デフォルト構築子 /// @param [in] stream ストリーム参照アドレス /// @param [in] indent インデント数 /// @param [in] header ヘッダー文字列 inline explicit TLogOut( std::ostream & stream = std::clog, int indent = m_defIndent, const char * header = 0 ) : m_ofs( 0 ), m_out( & stream ), m_indent( indent ), m_block( 0 ), m_header( header ) {} /// @brief ログファイル名指定構築子 /// @param [in] filename ファイル名 /// @param [in] indent インデントタブ空白数 /// @param [in] header ヘッダー文字列 inline explicit TLogOut( const char * filename, int indent = m_defIndent, const char * header = 0 ) : m_ofs( new std::ofstream( filename ) ), m_out( m_ofs ), m_indent( indent ), m_block( 0 ), m_header( header ) {} /// @brief 解体子 inline virtual ~TLogOut() { if ( m_ofs ) m_ofs->close(); } //-------------------------------------------------------------------- // 演算子オーバーロード関数 //-------------------------------------------------------------------- public : /// @brief 左シフト演算子オーバーロード関数 /// @param [in] param 引数 /// @return ログ出力ストリーム参照アドレス /// @details 引数をログストリームに出力します。 template< class T > std::ostream & operator <<( T & param ) const { return * m_out << param; } //-------------------------------------------------------------------- // 動的テンプレート関数 //-------------------------------------------------------------------- public : /// @brief データ出力関数 /// @param [in] name データ名 /// @param [in] value 値 /// @return ログ出力ストリーム参照アドレス /// @details データ名と値を出力します。 template< class T > std::ostream & DataValue( const char * name, T value ) const { // ヘッダーを出力します。 Header( m_block ); // データ名と値を出力します。 return * m_out << name << " = " << value << std::endl; } //-------------------------------------------------------------------- // 動的関数 //-------------------------------------------------------------------- public : /// @brief インデント数設定関数 /// @param [in] indent インデント数 /// @return ログ出力ストリーム参照アドレス /// @details インデント数を設定します。 inline virtual std::ostream & Indent( int indent ) { m_indent = indent; return * m_out; } /// @brief ヘッダー文字列設定関数 /// @param [in] header ヘッダー文字列 /// @return ログ出力ストリーム参照アドレス /// @details ヘッダー文字列を設定します。 inline virtual std::ostream & Header( const char * header ) { m_header = header; return * m_out; } /// @brief ヘッダー出力関数 /// @param [in] block ブロック数 /// @return ログ出力ストリーム参照アドレス /// @details ログヘッダー文字列を出力します。 inline virtual std::ostream & Header( int block ) const { // ヘッダー文字列を出力します。 if ( m_header ) * m_out << m_header; // ブロック数を巡回します。 for ( int n = 0; n < block; n++ ) { // インデント数を巡回します。 for ( int m = 0; m < m_indent; m++ ) { // 空白を出力します。 * m_out << " "; } } return * m_out; } /// @brief ブロック開始行出力関数 /// @param [in] name ブロック名 /// @return ログ出力ストリーム参照アドレス /// @details ブロック開始行を出力します。 inline virtual std::ostream & Begin( const char * name ) { // ヘッダーを出力してブロックカウンタをインクリメントします。 Header( m_block++ ); // ブロック開始文字とブロック名を出力します。 return * m_out << "{ " << name << std::endl; } /// @brief ブロック終了行出力関数 /// @param [in] name ブロック名 /// @return ログ出力ストリーム参照アドレス /// @details ブロック終了行を出力します。 inline virtual std::ostream & End( const char * name ) { // ブロックカウンタをデクリメントしてヘッダーを出力します。 Header( --m_block ); // ブロック終了文字とブロック名を出力します。 return * m_out << "} " << name << std::endl; } /// @brief 書式文字列出力関数 /// @param [in] format 書式文字列 /// @param [in] ... 可変引数 /// @return ログ出力ストリーム参照アドレス /// @details 書式付き文字列を出力します。 inline virtual std::ostream & Printf( const char * format, ... ) const { // ヘッダーを出力します。 Header( m_block ); // 展開後の文字列サイズを取得します。 va_list args; va_start( args, format ); size_t size = _vscprintf( format, args ) + 1; // 書式付き文字列をバッファーに展開します。 char * buffer = new char[ size ]; vsprintf_s( buffer, size, format, args ); // 展開された文字列を出力します。 * m_out << buffer << std::endl; // 文字列バッファーを削除します。 delete[] buffer; va_end( args ); return * m_out; } }; }
これだけだと標準ストリームとファイルストリームぐらいにしか出せないので、
どうせならいつもデバッグに使っているDebugOutputString()に出せるようにしたいと思いました。
そこでstd::ostreamクラスの派生クラスを作りました。
TDebogOut.h
//---------------------------------------------------------------------------- /// @file TDebugOut.h /// @brief デバッグ出力クラスヘッダ /// @details デバッグ出力クラスです。 //---------------------------------------------------------------------------- #pragma once #include "Common.h" #include <iostream> #include <windows.h> //---------------------------------------------------------------------------- // 共通ライブラリ名前空間 //---------------------------------------------------------------------------- namespace Common { //------------------------------------------------------------------------ /// @brief デバッグ出力クラス /// @details デバッグ出力クラスです。 //------------------------------------------------------------------------ class TDebugOut : public std::ostream { //-------------------------------------------------------------------- /// @brief ストリームバッファクラス /// @details ストリームバッファクラスです。 //-------------------------------------------------------------------- class TStreamBuf : public std::streambuf { //---------------------------------------------------------------- // 定数 //---------------------------------------------------------------- private : static const size_t m_blocksize = 256; ///< バッファーブロックサイズ //---------------------------------------------------------------- // 動的変数 //---------------------------------------------------------------- private : char * m_buffer; ///< 文字列バッファー size_t m_size; ///< バッファーサイズ size_t m_len; ///< 文字列長 //---------------------------------------------------------------- // 構築子と解体子 //---------------------------------------------------------------- public : /// @brief デフォルト構築子 inline explicit TStreamBuf() : std::streambuf(), m_buffer( 0 ), m_size( 0 ), m_len( 0 ) {} /// @brief 解体子 inline virtual ~TStreamBuf() { delete[] m_buffer; } //---------------------------------------------------------------- // 動的関数 //---------------------------------------------------------------- public : /// @brief オーバーフロー関数 /// @param [in] ch 文字コード /// @return 文字コード /// @details 1文字を書き込みます。 inline virtual int_type overflow( int_type ch = EOF ) { // EOF でないか調べます。 if ( ch != EOF ) { // バッファーサイズを調べます。 while ( m_size < m_len + 2 ) { // バッファーサイズを更新します。 if ( m_size += m_blocksize >= m_len + 2 ) { // 新規文字列バッファーを確保します。 char * buffer = new char[ m_size += m_blocksize ]; // 確保に失敗したか調べます。 if ( ! buffer ) throw( 0 ); // 現在のバッファー内容をコピーして削除します。 if ( m_buffer ) { memcpy( buffer, m_buffer, m_len + 1 ); delete[] m_buffer; } // バッファポインタを更新します。 m_buffer = buffer; break; } } // バッファーに書き込みます。 m_buffer[ m_len++ ] = ch; } return ch; } /// @brief 同期関数 /// @return 終了コード /// @details バッファー文字列を出力します。 inline virtual int sync() { // バッファー文字列をデバッグコンソールに出力します。 if ( m_buffer ) { m_buffer[ m_len ] = 0; OutputDebugStringA( m_buffer ); } // バッファーを削除します。 delete[] m_buffer; m_buffer = 0; m_size = 0; m_len = 0; return 0; } }; //-------------------------------------------------------------------- // 動的変数 //-------------------------------------------------------------------- private : std::streambuf * m_streambuf; ///< ストリームバッファー //-------------------------------------------------------------------- // 構築子と解体子 //-------------------------------------------------------------------- public : /// @brief デフォルト構築子 inline explicit TDebugOut() : std::ostream( m_streambuf = new TStreamBuf ) {} /// @brief 解体子 inline virtual ~TDebugOut() { delete m_streambuf; } }; }
はずかしい話ですが、DebugOutputStringA()の方でも漢字が出せるということを今まで知りませんでした。
もう恥ずかしくって"tchar.h"なんてインクルードできないです。
DLLで文字列定数を使うときの注意点
たぶんだけど、DLLで作ったクラス内で文字列定数をインラインで使用することはできない。
ていうかたぶん、ポインタを使うことはできないのではないのか。
それはたぶん、DLLだから実際にリンクされるまでアドレスが決定しないからなんだろね。
たとえば
class TClass { private : static const char * m_str1; const char * m_str2; public : inline TClass() : m_str2( m_str1 ) {} }; const char * TClass::m_str1 = "String";
これだとリンクエラーになるのだが、これを
class TClass { private : static const char * m_str1; const char * m_str2; public : TClass(); }; const char * TClass::m_str1 = "String"; TClass::TClass() : m_str2( m_str1 ) {}
これだとエラーにならないのだ。
マクロ定義されたトークンを文字列に変換するマクロ
Visual C++ 2010 Express 使ってるんですけど、
関数名とかは __FUNCTION__ とかで最初から文字列として定義されてるのに、
プロジェクト名とかは定義されてないんですよね。
ソリューション名とかプロジェクト名をソースコード中で使いたいとき、どうすれば良いんですか?ってんで、
とりあえずプロジェクトのコンパイルオプションプロパティで、Project=$(ProjectName)ってしたんですよ。
これを
#define STRING( token ) #token
的なやり方で文字列化すれば良いんじゃね?とか思ったんですよ。
でもこのやり方だと、STRING( Project )ってやると
"Project"っていう文字列が返ってきちゃうわけなんですよ。
こういう場合は、実はもう1回展開してやる必要があるみたいなんですね。なので
#define MACRO_STRING( macro ) STRING( macro )って定義して
MACRO_STRING( Project )ってやると、やっとプロジェクト名が文字列として取り出せるわけなんですよ。
これに気付くまでアホみたいに何時間もかかっちゃいました。
JanssonでJSONオブジェクトを並び順に表示するには
Janssonのjson_file_load()関数でJSONファイルを読み込むと、
JSONオブジェクトの中身は、ハッシュテーブル処理の関係ででたらめになりまが、
これを何とかJSONファイルの元の並び順にする方法を見つけましたので報告します。
それはjansson2.5のdump.cの中にやり方が書いてありました。
どおもJSONオブジェクト構造体にシリアル番号らしきメンバ変数があるので、
それを元にソートしてやれば良いみたいです。
// オブジェクトキー配列を作成します。 json_t * json = reinterpret_cast< json_t * >( const_cast< json_object_t * >( pJsonObject ) ), * value; size_t size = json_object_size( json ); struct object_key { size_t serial; const char * key; } * keys = new struct object_key[ size ]; memset( keys, 0, sizeof( struct object_key ) * size ); // JSONオブジェクトを巡回します。 size_t index = 0; for ( void * iter = json_object_iter( json ); iter; iter = json_object_iter_next( json, iter ), index++ ) { // シリアル値とキー文字列ポインタを設定します。 keys[ index ].serial = container_of( iter, hashtable_pair, list )->serial; keys[ index ].key = json_object_iter_key( iter ); } // JSONオブジェクトをシリアル値でソートします。 for ( index = 0; index < size - 1; index++ ) { for ( size_t index2 = index + 1; index2 < size; index2++ ) { if ( keys[ index ].serial > keys[ index2 ].serial ) { struct object_key tmp = keys[ index ]; keys[ index ] = keys[ index2 ]; keys[ index2 ] = tmp; } } } // オブジェクトキー配列を巡回します。 for ( index = 0; index < size; index++ ) { // オブジェクト名を表示します。 printf( "object[ %u ] : %s\n", index, keys[ index ].key ); // オブジェクト値を表示します。 value = json_object_iter_value( json_object_key_to_iter( keys[ index ].key ) ); PrintJsonValue( value ); } // オブジェクトキー配列を削除します。 delete[] keys;
詳細はこちらをご覧ください。
JSONファイルサンプル#1