C++基础:文件操作/目录/图像


文件流 fstream

头文件

定义了三个类型:

  • ifstream 从文件中读入数据
  • ofstream 将数据写入文件
  • fsream 读写给定文件

继承关系如下:
在这里插入图片描述

文件打开/关闭

在这里插入代码片

从文件读数据

写数据到文件

文件操作

跨平台接口

#ifdef WIN32
#include <io.h>
#include <direct.h>
#else
#include <unistd.h>
#include <sys/stat.h>
#endif

#ifdef WIN32
#define ACCESS(fileName,accessMode) _access(fileName,accessMode)
#define MKDIR(path) _mkdir(path)
#else
#define ACCESS(fileName, accessMode) access(fileName,accessMode)
#define MKDIR(path) mkdir(path,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
#endif

判断文件/目录是否存在

const char *folder = "../videos";
if (0 != ACCESS(folder, 0)) {
    int ret = MKDIR(folder);
}

读取目录下的所有文件名

#include <dirent.h>

void readImages(vector<string> &images, const string &path, int &num) {
    DIR *root = opendir(path.c_str());
    if (root == nullptr) {
        cerr << "Opendir failed!\n" << path.c_str() << endl;
        return;
    }

    int count = 0;
    struct dirent *ent;
    while (true) {
        ent = readdir(root);
        if (ent == nullptr) break;
        if (ent->d_name[0] != '.') {
            const std::string fileName = path + "/" + ent->d_name;
            if (fileExist(fileName)) {
                if (num == 0) {
                    images.push_back(fileName);
                    count++;
                } else if (count < num) {
                    images.push_back(fileName);
                    count++;
                } else {
                    break;
                }
            }
        }
    }
    num = count;
    cout << "using image num: " << num << endl;
}

读取图像文件 stb_image

#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION

#include "stb_image.h"
#include "stb_image_resize.h"
#include "stb_image_write.h"

void readImages(vector<string> &images, uint8_t *data, int width = 224, int height = 224, int num_channels = 3) {
    size_t size = width * height * num_channels;
    auto *dst_data = (uint8_t *) malloc(size);
    int num = images.size();
    for (int i = 0; i < num; i++) {
        int iw, ih, ich;
        uint8_t *src_data = stbi_load(images[i].c_str(), &iw, &ih, &ich, num_channels);
        stbir_resize_uint8(src_data, iw, ih, 0, dst_data, width, height, 0, num_channels);
        memcpy(data + size * i, dst_data, size);
        stbi_write_png("./test.png", width, height, num_channels, dst_data, 0);
        stbi_image_free(src_data);
    }
    stbi_image_free(dst_data);
}

获取当前的工作目录

#include  <direct.h>  

using namespace std;

string getCurrentWorkingDirectory() {
    char buffer[_MAX_PATH];
    _getcwd(buffer, _MAX_PATH);
    string path;
    // 将分隔符'\\'替换为'/'
    for (int i = 0; i < _MAX_PATH; i++) {
        if (i + 1 < _MAX_PATH && buffer[i] == '\\' && buffer[i + 1] == '\\') {
            continue;
        }
        else if (buffer[i] == '\\') {
            path.push_back('/');
        }
        else if (buffer[i] == '\0') {
            break;
        }
        else{
            path.push_back(buffer[i]);
        }
    }
    return path;
}

解析配置文件

将参数定义在头文件中:

#pragma once
#include <string>

extern int mode;
extern std::string video_path; 
extern std::string model_path;

void parse_params();

在c文件中进行解析:

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

using namespace std;

// config
int mode;
std::string video_path;
std::string model_path;

void strip_string(std::string &s) {
    std::string temp;
    for (char &c : s) {
        if (c != ' ' && c != '\t' && c != '\n') {
            temp += c;
        }
    }
    s = temp;
}

bool find_string(std::string &s, std::string contains_str) {
    auto a = s.find(contains_str);
    auto b = s.find('=');
    return b > a && a == b - contains_str.size();
}

void assign_params(string s) {
    if (find_string(s, "mode")) {
        int len = strlen("mode") + 1;
        mode = atoi(s.erase(0, len).c_str());
    } else if (find_string(s, "video_path")) {
        int len = strlen("video_path") + 1;
        video_path = s.erase(0, len);
    } else if (find_string(s, "model_path")) {
        int len = strlen("model_path") + 1;
        model_path = s.erase(0, len);
    } else {}
}

void parse_params() {
    string path = "params.cfg";
    ifstream f(path, std::ios::in);
    if (!f.is_open()) {
        cerr << "Failed to open file." << endl;
        exit(-1);
    }
    string line;
    while (getline(f, line)) {
        strip_string(line);
        switch (line[0]) {
            case '#':   // comment
            case ';':   // comment
            case '\0':  // blank
                break;
            default:    // config info
                assign_params(line);
        }
    }
    f.close();
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值