要基于C++11实现将IP地址、端口号和连接状态写入文件,您可以使用std::ofstream
类来打开文件并进行写入操作。以下是一个示例:
#include <iostream>
#include <fstream>void writeConnectionStatus(const std::string& ip, int port, bool isConnected) {std::ofstream file("connection_status.txt");if (!file.is_open()) {std::cerr << "Failed to open file" << std::endl;return;}file << "IP: " << ip << std::endl;file << "Port: " << port << std::endl;file << "Connection Status: " << (isConnected ? "Connected" : "Disconnected") << std::endl;file.close();
}int main() {std::string ip = "192.168.0.1";int port = 8080;bool isConnected = true;writeConnectionStatus(ip, port, isConnected);std::cout << "Connection status has been written to file." << std::endl;return 0;
}
在上述代码中,我们定义了writeConnectionStatus()
函数,该函数接受IP地址、端口号和连接状态作为参数。然后,我们使用std::ofstream
类创建一个名为connection_status.txt
的文件,并将相关信息写入文件中。
在主函数中,我们定义了IP地址、端口号和连接状态的示例值,并调用writeConnectionStatus()
函数将其写入文件。最后,我们打印一条消息来表示连接状态已成功写入文件。
请注意,根据需要修改文件名和路径,并根据具体情况进行适当的调整。同时,确保程序有足够的权限来创建和写入文件。