ESP32 LittleFS使用std::ofstream写入空格时读取异常问题
解决ESP32 LittleFS中C++ std::fstream读取截断问题
问题根源
你读取时使用的std::fstream >> read_data是按空白字符分割读取的:该运算符核心逻辑就是读取字符直到遇到空白字符(空格、换行、制表符等)就停止,哪怕设置了noskipws也不会改变这个行为——noskipws仅控制是否跳过输入前的空白,不影响>>的终止规则,所以你只读到了空格前的LittleFS1234。
解决方案
根据需求,推荐两种可靠的读取方式:
1. 读取整行内容(适合单行文本场景)
用std::getline替代>>,它会读取到换行符为止(默认不包含换行符):
// Open renamed file for reading ESP_LOGI(TAG, "Reading file"); std::fstream fo ("/littlefs/foo.txt", std::ios::in | std::ios::binary); if (!fo.is_open()) { ESP_LOGE(TAG, "Failed to open file for reading"); return; } std::string read_data; std::getline(fo, read_data); fo.close(); ESP_LOGI(TAG, "Read from file: '%s' (len: %d)", read_data.c_str(), read_data.size());
2. 读取文件全部内容(适合多行/二进制内容场景)
如果需要完整读取文件所有字节,可以通过文件指针定位获取大小后一次性读取:
// Open renamed file for reading ESP_LOGI(TAG, "Reading file"); std::fstream fo ("/littlefs/foo.txt", std::ios::in | std::ios::binary); if (!fo.is_open()) { ESP_LOGE(TAG, "Failed to open file for reading"); return; } // 获取文件大小 fo.seekg(0, std::ios::end); std::streampos file_size = fo.tellg(); fo.seekg(0, std::ios::beg); // 读取全部内容 std::string read_data(file_size, '\0'); fo.read(&read_data[0], file_size); fo.close(); ESP_LOGI(TAG, "Read from file: '%s' (len: %d)", read_data.c_str(), (int)file_size);
写入逻辑验证说明
你的写入代码是正常的,std::ofstream << std::string会完整写入包含空格和换行的字符串。如果仍怀疑写入问题,可以用ESP-IDF的C语言API(如fread)读取文件,或通过LittleFS工具直接查看闪存中的文件内容确认完整性。
内容的提问来源于stack exchange,提问作者tim687
相关产品推荐
相关产品推荐

