【c++】文件读写

该代码实现了一个从文件中读取数据并进行处理的程序。它检查文件是否存在,然后逐行读取,通过指定分隔符将字符串分割成多个部分,提取关键信息如图片路径、条件、坐标等。这个过程适用于解析包含结构化数据的文本文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

include <iostream>
#include <string>
#include <vector>
#include <typeinfo>

using namespace std;
using namespace cv;

// leetcode
void split_(const string& s, vector<string>& tokens, char delim = ' ') {
    tokens.clear();
    auto string_find_first_not = [s, delim](size_t pos = 0) -> size_t {
        for (size_t i = pos; i < s.size(); i++) {
            if (s[i] != delim) return i;
        }
        return string::npos;
    };   
    size_t lastPos = string_find_first_not(0);
    size_t pos = s.find(delim, lastPos);
    while (lastPos != string::npos) {
        tokens.emplace_back(s.substr(lastPos, pos - lastPos));
        lastPos = string_find_first_not(pos);
        pos = s.find(delim, lastPos);
    }
}


bool exist_file(const string &name){
    ifstream f(name.c_str());
    return f.good();
}

int main(void)
{
    // 读取标签文件
//    string const file = "123.txt";
    // file
    for(int i=0;i<200; i++){
        string file_path;
        file_path.append(path.c_str());
        file_path.append("/");
        file_path.append(to_string(i+1));
        file_path.append(file_end.c_str());
        
        bool file_flag;

        // 读取文件
        ifstream stream(file_path);
        char buffer[256];
        vector<string> position;
        string img_path, line;
        float cond;
        int x1,y1,x2,y2;

        // file_exist
        file_flag = exist_file(file_path);

        // get data
        while(file_flag && !(stream.eof())){
            stream.getline(buffer,256);
            line = string(buffer);

            if (line.length() > 0){  // have data
                // 字符串分割
                split_(line, position);

                // label info
                img_path = position[0];
                cond = atof(position[1].c_str());
                x1 = atoi(position[2].c_str());
                y1 = atoi(position[3].c_str());
                x2 = atoi(position[4].c_str());
                y2 = atoi(position[5].c_str());
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值