【小脚本】小脚本记录本

目录

1、C++计算程序耗时

2、C++计算程序耗时(基于opencv,需要头文件)

3、C++读写TXT文件

4、C++中执行终端指令(复制/移动文件等)

5、c++创建文件夹(判断文件夹是否存在,不存在则创建)


1、C++计算程序耗时

#include <time.h>  

clock_t start = clock();    //计时开始位置

//此处时需要执行的代码段

double duration = (double)(clock() - start) / CLOCKS_PER_SEC;  //计时结束位置,单位为秒
std::cout << "time: " << duration << "s" << std::endl;

2、C++计算程序耗时(基于opencv,需要头文件)

double start1 = static_cast<double>(cv::getTickCount());  //计时开始位置

double time1 = ((double)cv::getTickCount() - start1) / cv::getTickFrequency(); //计时结束位置,单位为秒
cout << "\t time : " << time1 << "s" << endl;

3、C++读写TXT文件

#include <iostream>
#include <fstream>

int main(){
    std::ifstream srcfile("/data_1/data/1.txt");     //读取txt
    std::ofstream outfile("/data_1/data/out.txt", ios::app); //ios::app指追加写入
    string temp;

    while (getline(srcfile, temp)) //按行读取字符串
    {
        outfile << temp<<endl;//写文件
    }
    srcfile.close();
    outfile.close();
    return 0;


    //读文件方法二:
    std::ofstream os;     //创建一个文件输出流对象
    os.open("/data_1/data/out.txt");//将对象与文件关联,若文件不存在,则新建一个文件;否则,直接输入内容(会覆盖原有内容)
    string str = "向文本中写入以下内容!";
    os << str;   //将输入的内容放入txt文件中
    os.close();
}

4、C++中执行终端指令(复制/移动文件等)

#include<stdlib.h>

string cmd = "cp " + file + " " + path;  //复制file到path路径下
system(cmd.c_str());  //system是在原进程上开辟了一个新的进程,执行系统指令

5、c++创建文件夹(判断文件夹是否存在,不存在则创建)

#include <direct.h>

string savePath = "/data_1/City/";
if (0 != access(savePath.c_str(), 0)){  // if this folder not exist, create a new one.
    mkdir(folderPath.c_str());   // 返回 0 表示创建成功,-1 表示失败
}

猜你喜欢

转载自blog.csdn.net/chen1234520nnn/article/details/111986587
今日推荐