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

来源:互联网 发布:mac双硬盘安装双系统 编辑:程序博客网 时间:2024/05/01 17:34

一、打开文件  

在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文本文件的读写

[cpp] view plain copy print?
  1. #include <iostream>  
  2. #include <fstream>  
  3. using namespace std;  
  4.   
  5. int main()   
  6. {  
  7.     ofstream out("F://IM_VIDEO//out.txt");  
  8. //  ifstream in("F://IM_VIDEO//in.txt");  
  9.     if (out.is_open())  
  10.     {  
  11.         out << "This is a line.\n";  
  12.         out << "This is another line.\n";  
  13.         out.close();  
  14.     }  
  15.     return 0;  
  16. }  

运行后发现,在相应目录下生成了txt文件out.txt,里面添加了两句话:this is a line. This is another line.

[cpp] view plain copy print?
  1. #include <iostream>  
  2. #include <fstream>  
  3. using namespace std;  
  4. //读取out.txt文件,并把其内容显示到屏幕中  
  5. int main()   
  6. {  
  7.     char buffer[256];  
  8.     ifstream in("F://IM_VIDEO//out.txt");  
  9.     if (!in.is_open())  
  10.     {  
  11.         cout << "Error opening file"; exit(1);  
  12.     }  
  13.     while (!in.eof())  
  14.     {  
  15.         in.getline(buffer, 100);  
  16.         cout << buffer << endl;  
  17.     }  
  18.     return 0;  
  19. }  

除了例子中的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 );

[cpp] view plain copy print?
  1. #include <iostream>  
  2. #include <fstream>  
  3. using namespace std;  
  4.   
  5. const char * filename = "F://IM_VIDEO//out.txt";  
  6. //获取文件字节数  
  7. int main() {  
  8.     long l, m;  
  9.     ifstream in(filename, ios::in | ios::binary);  
  10.     l = in.tellg();  
  11.     in.seekg(0, ios::end);  
  12.     m = in.tellg();  
  13.     in.close();  
  14.     cout << "size of  " << filename << " is " << (m - 1) << " bytes.\n" << endl;  
  15.     return 0;  
  16. }  

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):

[cpp] view plain copy print?
  1. //#include <iterator>  
  2. //#include <vector>  
  3. #include<opencv2\opencv.hpp>    
  4. #include<core/core.hpp>      
  5. #include<highgui/highgui.hpp>       
  6. #include<cv.h>  
  7. #include <iostream>  
  8. #include <fstream>  
  9.   
  10. using namespace std;  
  11. using namespace cv;  
  12. /* 
  13. * 功能 : 将 Mat 数据写入到 .txt 文件 
  14. * 函数 : WriteData 
  15. * 访问 : public 
  16. * 返回 : -1:打开文件失败;0:写入数据成功;1:矩阵为空 
  17. */  
  18. int WriteData(string fileName, Mat& matData)  
  19. {  
  20.     int retVal = 0;  
  21.     if (matData.empty())  
  22.     {  
  23.         cout << "矩阵为空" << endl;  
  24.         retVal = 1;  
  25.         return (retVal);  
  26.     }  
  27.   
  28.     // 打开文件  
  29.     ofstream outFile(fileName.c_str(), ios_base::out);  //按新建或覆盖方式写入  
  30.     if (!outFile.is_open())  
  31.     {  
  32.         cout << "打开文件失败" << endl;  
  33.         retVal = -1;  
  34.         return (retVal);  
  35.     }  
  36.   
  37.     // 写入数据  
  38.     for (int i = 0; i < matData.rows; i++)  
  39.     {  
  40.         uchar* pixelPtr = matData.ptr<uchar>(i);            //获取矩阵每行首地址指针    
  41.         for (int j = 0; j < matData.cols*matData.channels(); j++)  
  42.         {  
  43.             int data = pixelPtr[j];  
  44.             outFile << data<<"\t";  
  45.         }  
  46.         outFile << endl;  
  47.     }  
  48.     return (retVal);  
  49. }  
  50.   
  51. int main(int argc, char* argv[])  
  52. {  
  53.     Mat scr = imread("F://IM_VIDEO//kobe.jpg");  
  54.     WriteData("F://IM_VIDEO//kobe.txt", scr);  
  55. }  

上面程序可以将图像像素写入到自己命名的txt文件中。

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

[cpp] view plain copy print?
  1. #include<opencv2\opencv.hpp>    
  2. #include<core/core.hpp>      
  3. #include<highgui/highgui.hpp>       
  4. #include<cv.h>  
  5. #include <iostream>  
  6. #include <fstream>  
  7. #include <string>  
  8. using namespace std;  
  9. using namespace cv;  
  10.   
  11. void getFromText(String nameStr, Mat &myMat, uchar *pCurrentFace)  
  12. {  
  13.     String nameFaceStr;  
  14.     //nameFaceStr = nameStr + "kobe.txt";//the face file path  
  15.     ifstream myFaceFile;  
  16.     myFaceFile.open(nameFaceStr, ios::in);  
  17.     int temp;  
  18.     for (int r = 0; r < myMat.cols*myMat.rows*myMat.channels(); r++)  
  19.     {  
  20.         myFaceFile >> temp;  
  21.         pCurrentFace[r] = (uchar)temp;  
  22.     }  
  23.   
  24.     for (int i = 0; i < myMat.rows; i++)  
  25.     {  
  26.         uchar *pixelPtr = myMat.ptr<uchar>(i);  
  27.         for (int j = 0; j < myMat.cols*myMat.channels(); j++)  
  28.         {  
  29.             pixelPtr[j] = pCurrentFace[i*j+j];  
  30.         }  
  31.     }  
  32.     myFaceFile.close();  
  33. }  
  34.   
  35. int main(int argc, char* argv[])  
  36. {  
  37.     Mat scr = imread("F://IM_VIDEO//kobe.jpg");  
  38.     imshow("kobe", scr);  
  39.     Mat TrainData = Mat::zeros(scr.rows, scr.cols, CV_32FC3);  
  40.     imshow("juzhen", TrainData);  
  41.     uchar *pCurrentFace = (uchar*)malloc(scr.rows * scr.cols * 3 * sizeof(uchar));  
  42.     getFromText("F://IM_VIDEO//kobe.txt", TrainData, pCurrentFace);  
  43.     imshow("xianshi", TrainData);  
  44.     waitKey(0);  
  45. }  

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++)

原创粉丝点击