读取文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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
如封面所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#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;
}