读取文件夹

#include <fstream>
#include <unistd.h>
#include <dirent.h>
#include <string>
#include <vector>

int read_dir(std::string fileDir,std::vector<std::string>& files)
{
    struct dirent *ent = nullptr;
    DIR* dir = opendir(fileDir.c_str());
    if(dir)
    {
        while((ent = readdir(dir)) != nullptr)
        {
            if(strcmp(ent->d_name,".") != 0 && strcmp(ent->d_name,"..") != 0)
            {
                files.push_back(ent->d_name);
            }
        }
        return 0;
    }
    else
    {
        return -1;
    }
}

基于 cpp-httplib 写一个随机图片api
如封面所示

#include <iostream>
#include <bits/stdc++.h>
#include "cpp-httplib/httplib.h"
#include <unistd.h>
#include <dirent.h>
#include <fstream>

int idx2d = 0;

int read_dir(std::string fileDir,std::vector<std::string>& files)
{
    struct dirent *ent = nullptr;
    DIR* dir = opendir(fileDir.c_str());
    if(dir)
    {
        while((ent = readdir(dir)) != nullptr)
        {
            if(strcmp(ent->d_name,".") != 0 && strcmp(ent->d_name,"..") != 0)
            {
                files.push_back(ent->d_name);
            }
        }
        return 0;
    }
    else
    {
        return -1;
    }
}

int main()
{
    daemon(1, 0); // 后台运行
    httplib::Server svr;
    std::vector<string> files2d;
    
    svr.Get("/2D", [&files2d,&idx2d](const httplib::Request &, httplib::Response &res)
    {
        files2d.clear();
        read_dir("./data/2D",files2d);
        if(idx2d == files2d.size())
        {
            idx2d = 0;
        }
        string file_name = "./data/2D/" + files2d[idx2d++];
        ifstream fin(file_name.c_str(),ios::binary);
        ostringstream os;
        os << fin.rdbuf();
        std::string content = os.str();
        fin.close();
        res.set_content(content,"image/webp");
    });
    svr.listen("0.0.0.0", 9876);
    return 0;
}