目录
1普通读写
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void writeTXT(string name, string content, bool cover);
//如果没有就创建
void readTxtShow(string name);
int main() {
//创建以及writeTXT
writeTXT("label.txt", "hello world!", false);
//true为覆盖,false为接着写
//read入TXT并显示
readTxtShow("label.txt");
}
void writeTXT(string name, string content ,bool cover) {
ofstream write(name, cover ? ios::trunc : ios::app);
if (write.is_open())
{
write << content << endl;
write.close();
}
}
void readTxtShow(string name) {
fstream file;
file.open(name);
while (!file.eof())
{
string s1;
file >> s1;
cout << s1 << endl;
}
file.close();
}
2循环读写(存在小瑕疵)
#include <iostream>
#include <fstream>
#include <string>
#include <opencv2/opencv.hpp>
#include <time.h>
#include <ctime>
#include <sys/time.h>
using namespace std;
void write_txt(string name, string content ,bool cover) {
ofstream write(name, cover ? ios::trunc : ios::app);
if (write.is_open())
{
write << content << endl;
write.close();
}
}
void readShow_txt(string name) {
fstream file;
file.open(name);
while (!file.eof())
{
string s1;
file >> s1;
cout << s1 << endl;
}
file.close();
}
long tickCount()
{
static struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
int file2list(const char *imageLists, std::vector<std::string> &lists)
{
lists.clear();
std::ifstream file;
file.open(imageLists);
char str[200];
int num=0;
// 存在问题,这里多读入了一行,所以下面的代码才使用的是 images.size()-1
while(!file.eof())
{
memset(str,0,200);
file.getline(str,200);
lists.push_back(std::string(str));
//std::cout<<"111111 "<<std::string(str)<<std::endl;
num++;
}
return num;
}
int main() {
std::string imgs = "./JPEGImages/";
std::string save = "./save/";
std::string txtSave = "./txtResults/";
const char *imagesList = "./list.txt";
std::vector<std::string> images;
file2list(imagesList, images);
std::string txtsLine1;
std::string txtsLine2;
for(int i=0;i<images.size()-1;i++)
{
cv::Mat img = cv::imread(imgs+images[i]+".jpg");
if(img.cols == 0)
continue;
long s = tickCount();
//目标检测
std::cout<<"detect time "<<(tickCount()-s)<<std::endl;
write_txt(txtSave+images[i]+".txt",txtsLine2,true);
cv::imwrite(save+images[i]+".jpg", img);
}
//创建以及writeTXT
write_txt("label.txt", "hello world!", false);
//true为覆盖,false为接着写
//read入TXT并显示
readShow_txt("label.txt");
}