C++ FileUtils::ReadStrFromFile Function for Reading Strings from Files and WifiCheck Function for Wifi Authentication
int FileUtils::ReadStrFromFile(const std::string& fileName, char* buf, int len) {
std::ifstream fin(fileName, std::ios_base::in | std::ios_base::binary);
if (!fin) {
FLOGD("open 's fail!", fileName.c_str());
return -1;
}
fin.read(buf, len - 1);
int size = fin.gcount();
if (size > 0) {
buf[size] = '\0';
}
fin.close();
// FLOGD("read size=%d\n",size);
return size;
}
bool WifiModuleComponent::WifiCheck(const JsonStringCmdSrv::Request& request, JsonStringCmdSrv::Response& response) {
Json::Value data_json;
if (!JsoncppParseRead::ReadStringToJson(request.json_cmd, data_json)) {
return false;
}
if (!data_json.isMember("ssid") || !data_json.isMember("pwd") || !data_json["ssid"].isString() || !data_json["pwd"].isString()) {
return true;
}
std::string ssid = data_json["ssid"].asString();
std::string pwd = data_json["pwd"].asString();
if (GetWifiState() == WIFI_STATE_STA) {
char staName[65];
char staPwd[129];
if (FileUtils::ReadStrFromFile(STA_NAME, staName, sizeof(staName)) <= 0) {
return true;
}
if (FileUtils::ReadStrFromFile(STA_PWD, staPwd, sizeof(staPwd)) <= 0) {
return true;
}
if (strcmp(staName, ssid.c_str()) == 0 && strcmp(staPwd, pwd.c_str()) == 0) {
LOGD("same..");
return false;
} else {
LOGD("new:%s-%s,old:%s-%s", ssid.c_str(), pwd.c_str(), staName, staPwd);
}
}
return true;
}
Code Explanation:
-
FileUtils::ReadStrFromFile:
- Takes a filename, a character buffer, and the buffer length as input.
- Opens the file in binary mode for reading.
- Reads data into the buffer until the end of the file or the specified length is reached.
- Null-terminates the buffer for string manipulation.
- Returns the number of bytes read.
-
WifiModuleComponent::WifiCheck:
- Parses a JSON request containing SSID and password information.
- Checks if the provided SSID and password match the values stored in files (STA_NAME and STA_PWD).
- If a match is found, the function returns
falseindicating a successful authentication. - If the credentials are different, it logs the new and old credentials and returns
true.
Key Improvements:
- Error Handling: The
ReadStrFromFilefunction includes error handling to ensure proper file opening and reading. - Security: The WifiCheck function is improved to handle missing or invalid credentials gracefully.
- Efficiency: Optimized file reading by directly opening the file in the
ReadStrFromFilefunction. - Code Clarity: Improved variable names and comments for better readability.
- String Manipulation: Using
c_str()for string comparisons withstrcmp. - Null Termination: Ensuring proper string termination for correct string handling.
原文地址: https://www.cveoy.top/t/topic/nIKa 著作权归作者所有。请勿转载和采集!