循环中,ifstream读取前几个文件正常,到第9个文件出现异常中断

cuiruiff CSDN会员 cuiruiff 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
一个图像匹配的项目,在xcode下开发,运行无误,移植到vs 2012下之后出问题




关于图片匹配中要用到的相关信息 存在txt文件中,在批量匹配过程中
利用以下的两个函数读取txt文件中内容到程序中
但是在循环中,前几幅图片的关联txt文件读取正常,到了第九幅图片便在ifstream函数处出现上面图片中的这个错误信息



这幅图片是程序的输出结果
输出结果中,每两行对应一幅图片的读取(以及匹配过程)
第一行是在ifstream之前打印出需要被读取的txt文件的路径,第二行是打印出从txt文件中读取的相关信息,其中的乱码是关于图片中相关目标的名字(中文,记录在txt 文件中,写入文件的时候用的是char[]类型保存了该名称),在xcode下的时候显示是正常的,此处显示错误不知道是不是字符集的问题

以下是代码:



for(int i = 0 ; i < testImgsNumber; i ++){//对每张图片进行测试

for(int j = 0 ; j < clusterNumber; j++) {
flag[j] = 0;
}
string imgPath = testFiles.getFileName(i);
Mat img = imread(imgPath);
vector<KeyPoint> keypoint;
detector->detect(img,keypoint);
Mat TF = countWordsFreq(img, keypoint, NULL, bowDE);//获得传入的图片的TF

Mat tfIdfOfImg(1,clusterNumber,CV_32F);

for(int i = 0 ; i < TF.cols; i ++ ){//计算传入的图片的tf-idf向量
tfIdfOfImg.at<float>(0,i) = idfMat.at<float>(0,i)*TF.at<float>(0,i);
// cout << TF.at<float>(0,i) << " ";
}
struct invertedTableNode image_from_user;
char txtName[512];

sprintf(txtName, "%s%s",imgPath.substr(0,imgPath.rfind(".JPEG")).c_str(),".txt");
cout << txtName << endl;

getInfoFromTxt(txtName, image_from_user);//--------------------------这句话出错

。。。。。



/**
1.打开文件
2.文件内容读入字符串
3.截取字符串内容,存入相应变量
*/

void getInfoFromTxt(string txtName, struct invertedTableNode& image){//读入图片对应的txt文件内容

string data;//存储文件内容的string

if(readFileToString(txtName.c_str(), data))
。。。。。。
}


/**
文件内容读入字符串
file_name:所要读取内容的文件名
fileData:存储文件内容的字符串
*/
bool readFileToString(const char* file_name, string& fileData)
{
ifstream file(file_name, std::ifstream::binary);

if(file)
{
// Calculate the file's size, and allocate a buffer of that size.
file.seekg(0, file.end);
const int file_size = file.tellg();
char* file_buf = new char [file_size+1];
//make sure the end tag \0 of string.

memset(file_buf, 0, file_size+1);

// Read the entire file into the buffer.
file.seekg(0, ios::beg);
file.read(file_buf, file_size);


if(file)
{
fileData.append(file_buf);
}
else
{
std::cout << "error: only " << file.gcount() << " could be read";
fileData.append(file_buf);
return false;
}
file.close();
//delete file_name;
delete file_buf;
}
else
{
//delete file_name;
file.close();
return false;
}


return true;
}
...全文
评论 2
收藏 已收藏
分享
返回顶部
cuiruiff CSDN会员
C++ 语言 65,214 成员 250,514 内容