c++ 常用小函數

#include  <fstream>

using namespace std;
int main(int argc,char* argv[])
{
    map<string, string> data;

    ifstream fin(argv[1]);
    //ifstream in("...", ios::in); 
    if(!fin)
    {
        cout<<"can not open"<< argv[1]<<endl;
        return -1;
    }

    while(!fin.eof())
    {
        string str;
        getline(fin,str);

        if (str[0] == '#')
        {
            // 以‘#’開頭的是註釋
            continue;
        }

        int pos = str.find(":");
        if (pos == -1)
            continue;
        std::string key = str.substr( 0, pos );
        std::string value = str.substr( pos+2, str.length()-pos-2 );
        data[key] = value;

        if ( !fin.good() )
            break;
     }
}

#include  <fstream>

ofstream out; 
outputDistMap.open("../txtFiles/DistMaps.txt");
//ofstream out("...");
out << "idx=" <<idx<< endl;

string to float

std::string resolution_=data["resolution"];
resolution=atof(resolution_.c_str());

int to string

#include <stdlib.h>
int a=2;
char temp[4];
sprintf(temp,"%d",a);
string b=temp;

時間測試

#include "time.h"

clock_t start, finish;
double duration;
start = clock();
...
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC; 

從路徑中讀取所有文件

utils.h

#ifndef CUIZHOU_JNI_OPENCV_SSD_MOBILENET_DEMO_UTIL_H
#define CUIZHOU_JNI_OPENCV_SSD_MOBILENET_DEMO_UTIL_H

#include <stdlib.h>
#include <dirent.h>
#include <string>
#include <vector>

std::vector<std::string> readFileList(char *basePath);
#endif //CUIZHOU_JNI_OPENCV_SSD_MOBILENET_DEMO_UTIL_H

utils.cpp


std::vector<std::string> readFileList(char *basePath)
{
    std::vector<std::string> result;
    DIR *dir;
    struct dirent *ptr;
    char base[1000];

    if ((dir=opendir(basePath)) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }

    while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)
            continue;
        else if(ptr->d_type == 8)    ///file
        {printf("d_name:%s/%s\n",basePath,ptr->d_name);
            result.push_back(std::string(ptr->d_name));}
        else if(ptr->d_type == 10)    ///link file
        {printf("d_name:%s/%s\n",basePath,ptr->d_name);
            result.push_back(std::string(ptr->d_name));}
        else if(ptr->d_type == 4)    ///dir
        {
            memset(base,'\0',sizeof(base));
            strcpy(base,basePath);
            strcat(base,"/");
            strcat(base,ptr->d_name);
            result.push_back(std::string(ptr->d_name));
            readFileList(base);
        }
    }
    closedir(dir);
    return result;
}

關於字符串的操作:
https://www.renfei.org/blog/introduction-to-cpp-string.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章