您的位置:首页 > 编程语言 > C语言/C++

C++读写txt文件方式以及基于opencv的Mat数据类型读写txt文件类型

2017-03-09 15:40 1011 查看
在c++中常常使用的读写函数有:ofstream,ifstream,fstream,

可以参见:http://blog.csdn.net/kingstar158/article/details/6859379/http://blog.csdn.net/augusdi/article/details/8865378



在C++中,有一个stream类,所有的I/O都以这个“流”类为基础的,包括要认识的文件I/O,stream这个类有两个重要的运算符:

1、插入器(<<)  向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<'\n';就表示把字符串"Write Stdout"和换行字符('\n')输出到标准输出流。

2、析取器(>>)  从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。

  在C++中,对文件的操作是通过stream的子类fstream(file stream)来实现的,要用这种方式操作文件,须加入头文件fstream。

一、打开文件  

在fstream类中,有一个成员函数open(),就是用来打开文件的,其原型是:

void open(const char* filename,int mode,int access);

参数:

filename:要打开的文件名

mode:要打开文件的方式

access:打开文件的属性  //基本很少用到

打开文件的方式在类iOS(是所有流式I/O类的基类)中定义,常用的值如下:

ios::in为输入(读)而打开文件
ios::out为输出(写)而打开文件
ios::ate初始位置:文件尾
ios::app所有输出附加在文件末尾
ios::trunc如果文件已存在则先删除该文件
ios::binary二进制方式
可以用“或”把以上属性连接起来,如ios::out|ios::binary

打开文件的属性同样在ios类中也有定义:

0普通文件,打开操作
1只读文件
2隐含文件
4系统文件
对于文件的属性也可以使用“或”运算和“+”进行组合使用。

二、关闭文件  

打开的文件使用完成后一定要关闭,fstream提供了成员函数close()来完成此操作,如:file1.close();就把file1相连的文件关闭。

三、读写文件  

读写的文件分为文本文件和二进制文件,对于文本文件的读取比较简单,用插入器和析取即可,而对于二进制的读取就要复杂些。

3.1文本文件的读写

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream out("F://IM_VIDEO//out.txt");
// ifstream in("F://IM_VIDEO//in.txt");
if (out.is_open())
{
out << "This is a line.\n";
out << "This is another line.\n";
out.close();
}
return 0;
}运行后发现,在相应目录下生成了txt文件out.txt,里面添加了两句话:this is a line. This is another line.
#include <iostream>
#include <fstream>
using namespace std;
//读取out.txt文件,并把其内容显示到屏幕中
int main()
{
char buffer[256];
ifstream in("F://IM_VIDEO//out.txt");
if (!in.is_open())
{
cout << "Error opening file"; exit(1);
}
while (!in.eof())
{
in.getline(buffer, 100);
cout << buffer << endl;
}
return 0;
}
除了例子中的eof,它是ifstream 从类 ios 中继承过来的成员函数。另外还有状态标志符的验证(Verification of state flags)

bad()

如果在读写过程中出错,返回 true 。例如:当我们要对一个不是打开为写状态的文件进行写入时,或者我们要写入的设备没有剩余空间的时候。

fail()

除了与bad() 同样的情况下会返回 true 以外,加上格式错误时也返回true ,例如当想要读入一个整数,而获得了一个字母的时候。

eof()

如果读文件到达文件末尾,返回true。

good()

这是最通用的:如果调用以上任何一个函数返回true 的话,此函数返回 false 。

获得和设置流指针(get and put stream pointers):

所有输入/输出流对象(i/o streams objects)都有至少一个流指针:

ifstream, 类似istream, 有一个被称为get pointer的指针,指向下一个将被读取的元素。

ofstream, 类似 ostream, 有一个指针 put pointer ,指向写入下一个元素的位置。

fstream, 类似 iostream, 同时继承了get 和 put

可以通过使用成员函数:tellg() 和 tellp()来读出或配置这些指向流中读写位置的流指针
tellg() 和 tellp()

这两个成员函数不用传入参数,返回pos_type 类型的值(根据ANSI-C++ 标准) ,就是一个整数,代表当前get 流指针的位置 (用tellg) 或 put 流指针的位置(用tellp).
seekg() 和seekp()

这对函数分别用来改变流指针get 和put的位置。两个函数都被重载为两种不同的原型:

seekg ( pos_type position );

seekp ( pos_type position );

使用这个原型,流指针被改变为指向从文件开始计算的一个绝对位置。要求传入的参数类型与函数 tellg 和tellp 的返回值类型相同。

seekg ( off_type offset, seekdir direction );

seekp ( off_type offset, seekdir direction );

#include <iostream>
#include <fstream>
using namespace std;

const char * filename = "F://IM_VIDEO//out.txt";
//获取文件字节数
int main() {
long l, m;
ifstream in(filename, ios::in | ios::binary);
l = in.tellg();
in.seekg(0, ios::end);
m = in.tellg();
in.close();
cout << "size of " << filename << " is " << (m - 1) << " bytes.\n" << endl;
return 0;
}

3.2二进制文件的读写

(1)put()

  put()函数向流写入一个字符,其原型是ofstream &put(char ch),使用也比较简单,如file1.put('c');就是向流写一个字符'c'。
(2)get()

  get()函数比较灵活,有3种常用的重载形式:
  1.和put()对应的形式:ifstream &get(char &ch);功能是从流中读取一个字符,结果保存在引用ch中,如果到文件尾,返回空字符。如file2.get(x);表示从文件中读取一个字符,并把读取的字符保存在x中。
  2.重载形式。原型是:int get();从流中返回一个字符,如果到达文件尾,返回EOF,如x=file2.get();和上例功能是一样的。
  3.ifstream &get(char *buf,int num,char delim='n');这种形式把字符读入由 buf 指向的数组,直到读入了 num 个字符或遇到了由 delim 指定的字符,如果没使用 delim 这个参数,将使用缺省值换行符'n'。例如:
  file2.get(str1,127,'A');//从文件中读取字符到字符串str1,当遇到字符'A'或读取了127个字符时终止。
(3)读写数据块

  在二进制文件中,使用<< 和>>,以及函数(如getline)来操作符输入和输出数据。要读写二进制数据块,使用成员函数read()和write()成员函数,它们原型如下:
  read(unsigned char *buf,int num);

  write(const unsigned char *buf,int num);
  这里 buffer 是一块内存的地址,用来存储或读出数据。参数num是一个整数值,表示要从缓存(buffer)中读出或写入的字符数。read()从文件中读取 num 个字符到
buf 指向的缓存中,如果在还未读入 num 个字符时就到了文件尾,可以用成员函数 int gcount();来取得实际读取的字符数;而 write() 从buf 指向的缓存写 num 个字符到文件中,值得注意的是缓存的类型是 unsigned char *,有时可能需要类型转换。

opencv读写txt文件:

现使用opencv对图像Mat类型读写txt文件进行汇总~

首先将一幅图像写入txt文件中(实例1):

//#include <iterator>
//#include <vector>
#include<opencv2\opencv.hpp>
#include<core/core.hpp>
#include<highgui/highgui.hpp>
#include<cv.h>
#include <iostream>
#include <fstream>

using namespace std;
using namespace cv;
/*
* 功能 : 将 Mat 数据写入到 .txt 文件
* 函数 : WriteData
* 访问 : public
* 返回 : -1:打开文件失败;0:写入数据成功;1:矩阵为空
*/
int WriteData(string fileName, Mat& matData)
{
int retVal = 0;
if (matData.empty())
{
cout << "矩阵为空" << endl;
retVal = 1;
return (retVal);
}

// 打开文件
ofstream outFile(fileName.c_str(), ios_base::out); //按新建或覆盖方式写入
if (!outFile.is_open())
{
cout << "打开文件失败" << endl;
retVal = -1;
return (retVal);
}

// 写入数据
for (int i = 0; i < matData.rows; i++)
{
uchar* pixelPtr = matData.ptr<uchar>(i); //获取矩阵每行首地址指针
for (int j = 0; j < matData.cols*matData.channels(); j++)
{
int data = pixelPtr[j];
outFile << data<<"\t";
}
outFile << endl;
}
return (retVal);
}

int main(int argc, char* argv[])
{
Mat scr = imread("F://IM_VIDEO//kobe.jpg");
WriteData("F://IM_VIDEO//kobe.txt", scr);
}
上面程序可以将图像像素写入到自己命名的txt文件中。

将txt中的数据写入Mat类型文件中,并保存为图片格式(实例2):

#include<opencv2\opencv.hpp>
#include<core/core.hpp>
#include<highgui/highgui.hpp>
#include<cv.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using namespace cv;

void getFromText(String nameStr, Mat &myMat, uchar *pCurrentFace)
{
String nameFaceStr;
//nameFaceStr = nameStr + "kobe.txt";//the face file path
ifstream myFaceFile;
myFaceFile.open(nameFaceStr, ios::in);
int temp;
for (int r = 0; r < myMat.cols*myMat.rows*myMat.channels(); r++)
{
myFaceFile >> temp;
pCurrentFace[r] = (uchar)temp;
}

for (int i = 0; i < myMat.rows; i++)
{
uchar *pixelPtr = myMat.ptr<uchar>(i);
for (int j = 0; j < myMat.cols*myMat.channels(); j++)
{
pixelPtr[j] = pCurrentFace[i*j+j];
}
}
myFaceFile.close();
}

int main(int argc, char* argv[])
{
Mat scr = imread("F://IM_VIDEO//kobe.jpg");
imshow("kobe", scr);
Mat TrainData = Mat::zeros(scr.rows, scr.cols, CV_32FC3);
imshow("juzhen", TrainData);
uchar *pCurrentFace = (uchar*)malloc(scr.rows * scr.cols * 3 * sizeof(uchar));
getFromText("F://IM_VIDEO//kobe.txt", TrainData, pCurrentFace);
imshow("xianshi", TrainData);
waitKey(0);
}
but,,,这个有问题,暂时没找到正确的办法,请赐教、、、

参考:
http://blog.csdn.net/ljh0600301217/article/details/8731190 http://blog.csdn.net/bendanban/article/details/30306505?utm_source=tuicool&utm_medium=referral (MATLAB,c++)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Mat txt opencv
相关文章推荐