yaml写入
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE *fs = fopen("test.yml", "w");
if (!fs)
{
fprintf(stderr, "Failed to open file for writing.\n");
return -1;
}
fprintf(fs, "frameCount: %d\n", 5);
time_t rawtime;
time(&rawtime);
fprintf(fs, "calibrationDate: %s", asctime(localtime(&rawtime)));
fprintf(fs, "cameraMatrix: !!opencv-matrix\n");
fprintf(fs, " rows: 3\n");
fprintf(fs, " cols: 3\n");
fprintf(fs, " dt: d\n");
fprintf(fs, " data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]\n");
fprintf(fs, "distCoeffs: !!opencv-matrix\n");
fprintf(fs, " rows: 5\n");
fprintf(fs, " cols: 1\n");
fprintf(fs, " dt: d\n");
fprintf(fs, " data: [ 0.1, 0.01, -0.001, 0., 0. ]\n");
fprintf(fs, "features:\n");
fprintf(fs, "-\n");
for (int i = 0; i < 3; i++)
{
int x = rand() % 640;
int y = rand() % 480;
unsigned char lbp = rand() % 256;
fprintf(fs, " x: %d\n", x);
fprintf(fs, " y: %d\n", y);
fprintf(fs, " lbp: [");
for (int j = 0; j < 8; j++)
{
fprintf(fs, " %d", (lbp >> j) & 1);
}
fprintf(fs, " ]\n");
}
fclose(fs);
return 0;
}
yaml读取
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
// 从文件中读取数据
FILE *fs2 = fopen("test.yml", "r");
if (!fs2)
{
fprintf(stderr, "Failed to open file for reading.\n");
return -1;
}
// 从文件中读取数据并进行相应的处理
int frameCount;
fscanf(fs2, "frameCount: %d\n", &frameCount);
char date[100];
fscanf(fs2, "calibrationDate: %s", date);
printf("frameCount: %d\n", frameCount);
printf("calibration date: %s\n", date);
// 读取矩阵数据,这里省略了矩阵数据的详细处理
// ...
// 读取特征数据,这里也只是一个简化的示例
int x, y;
char lbp[8];
for (int i = 0; i < 3; i++)
{
fscanf(fs2, "x: %d\n", &x);
fscanf(fs2, "y: %d\n", &y);
fscanf(fs2, "lbp: [ %c %c %c %c %c %c %c %c ]\n", &lbp[0], &lbp[1], &lbp[2], &lbp[3], &lbp[4], &lbp[5], &lbp[6], &lbp[7]);
printf("feature #%d: x=%d, y=%d, lbp: (%s %s %s %s %s %s %s %s)\n", i, x, y, lbp[0], lbp[1], lbp[2], lbp[3], lbp[4], lbp[5], lbp[6], lbp[7]);
}
fclose(fs2);
return 0;
}
ini文件读取
#include <stdio.h>
#include <string.h>
int main()
{
// 打开配置文件
FILE *config_file = fopen("config.txt", "r");
if (!config_file)
{
fprintf(stderr, "Failed to open config file.\n");
return -1;
}
char line[100]; // 假设一行最多100个字符
while (fgets(line, sizeof(line), config_file))
{
// 去除行尾的换行符
line[strcspn(line, "\n")] = 0;
// 如果是注释或空行,则忽略
if (line[0] == '#' || line[0] == '\0')
continue;
// 解析key-value对
char *pos = strchr(line, '=');
if (pos != NULL)
{
*pos = '\0'; // 将等号替换为字符串结束符
char *key = line;
char *value = pos + 1;
printf("Key: %s, Value: %s\n", key, value);
}
}
// 关闭文件
fclose(config_file);
return 0;
}