【文件IO】按行读取 / 写入某个文件中的内容

1、按行读取 

#include <fstream>
#include <sstream>
#include <iostream>
#include <string>

/* 将字符串转换成数值类型(需为内置类型) */
template<class T>
T str2Type(const std::string& str)
{
    std::istringstream iss(str);
    T num;
    iss >> num;
    return num;
}

void readTemp(const std::string& filePath, std::vector<double>* output)
{
    std::ifstream ifs(filePath.c_str());
    if (!ifs.is_open())
    {
        perror("failed to open file");
        return;
    }

    std::string line;
    while (getline(ifs, line))
    {
        ssize_t pos = line.find_last_of(";");           // 查找指定符号
        std::string data = line.substr(pos + 1);        // 截取部分内容


        std::cout << str2Type<double>(data) << std::endl;    // 字符串转double
    }
}

2、按行写入

void writeTemp(const std::vector<double>& input, const std::string& filePath)
{
    std::ofstream ofs(filePath, std::ofstream::trunc);
    if (!ofs.is_open())
    {
        perror("failed to open file");
        return;
    }

    for (size_t i = 0; i < input.size(); i++)
    {
        ofs << input[i] << "\n";
    }
}

猜你喜欢

转载自blog.csdn.net/challenglistic/article/details/131261334