ファイルオープンから構造体へのデータセットまでを別モジュールにするために、以下の手順に従ってプログラムを変更します。
新しいヘッダファイルを作成します。例えば、"wifi_data.h"という名前のファイルを作成します。
"wifi_data.h"ファイルに、必要なヘッダファイルと構造体の宣言を移動します。以下は、"wifi_data.h"ファイルの例です。
#ifndef WIFI_DATA_H #define WIFI_DATA_H #include <string> #include <vector> struct WiFiAccessPoint { std::string ssid; std::string mode; std::string channel; std::string signal; std::string security; }; std::vector<WiFiAccessPoint> readWiFiDataFromFile(const std::string& filename); #endif
新しいソースファイルを作成します。例えば、"wifi_data.cpp"という名前のファイルを作成します。
"wifi_data.cpp"ファイルに、ファイルからデータを読み込む関数を定義します。以下は、"wifi_data.cpp"ファイルの例です。
#include "wifi_data.h" #include <fstream> #include <iostream> #include <sstream> std::vector<std::string> splitString(const std::string& str, char delimiter) { std::vector<std::string> tokens; std::stringstream ss(str); std::string token; while (std::getline(ss, token, delimiter)) { tokens.push_back(token); } return tokens; } std::vector<WiFiAccessPoint> readWiFiDataFromFile(const std::string& filename) { std::vector<WiFiAccessPoint> accessPoints; std::ifstream file(filename); if (!file.is_open()) { std::cerr << "ファイルの読み込みに失敗しました。" << std::endl; return accessPoints; } std::string line; std::getline(file, line); // ヘッダ行を読み飛ばす while (std::getline(file, line)) { std::vector<std::string> tokens = splitString(line, ' '); if (tokens.size() >= 5) { WiFiAccessPoint ap; ap.ssid = tokens[0]; ap.mode = tokens[1]; ap.channel = tokens[2]; ap.signal = tokens[3]; ap.security = tokens[4]; accessPoints.push_back(ap); } } file.close(); return accessPoints; }
- メインのソースファイル(現在のプログラム)を変更します。
#include <iostream> #include <vector> #include <fstream> #include <sstream> #include <cstring> #include "wifi_data.h" // 新しいヘッダファイルをインクルード int main() { std::string command = "nmcli device wifi list > wifi_list.txt"; FILE* pipe = popen(command.c_str(), "r"); if (!pipe) { std::cerr << "コマンドの実行に失