c/c++、MATLAB读写文件

目录

1 c语言读写文件

1.1 c语言写文件

1.2 c语言读文件

2 c++读写文件

2.1 文本文件

2.1.1 写文件

2.1.2 读文件

2.2 二进制文件,bin文件

2.2.1 写文件

2.2.2 读文件

3 MATLAB读写文件

3.1 MATLAB读文件

3.2 MATLAB写文件


引用参考:菜鸟教程

打开文件

使用 fopen( ) 函数来创建一个新的文件或者打开一个已有的文件,这个调用会初始化类型 FILE 的一个对象,类型 FILE 包含了所有用来控制流的必要的信息。下面是这个函数调用的原型:

FILE *fopen( const char * filename, const char * mode );

在这里,filename 是字符串,用来命名文件,访问模式 mode 的值可以是下列值中的一个:

模式描述
r打开一个已有的文本文件,允许读取文件。
w打开一个文本文件,允许写入文件。如果文件不存在,则会创建一个新文件。在这里,您的程序会从文件的开头写入内容。如果文件存在,则该会被截断为零长度,重新写入。
a打开一个文本文件,以追加模式写入文件。如果文件不存在,则会创建一个新文件。在这里,您的程序会在已有的文件内容中追加内容。
r+打开一个文本文件,允许读写文件。
w+打开一个文本文件,允许读写文件。如果文件已存在,则文件会被截断为零长度,如果文件不存在,则会创建一个新文件。
a+打开一个文本文件,允许读写文件。如果文件不存在,则会创建一个新文件。读取会从文件的开头开始,写入则只能是追加模式。

如果处理的是二进制文件,则需使用下面的访问模式来取代上面的访问模式:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

关闭文件

关闭文件,使用 fclose( ) 函数。函数的原型如下:

 int fclose( FILE *fp );

1 c语言读写文件

1.1 c语言写文件

写入txt文件

#include "stdlib.h"
#include<stdio.h>

int saveDataToTXT(double y[], int length, const char* filePath) {
	int i = 0;

	FILE *fp;
	fp = fopen(filePath, "wb"); //数据导出
	if (fp == NULL)
	{
		printf("cant open the file");
		exit(0);
	}

	for (i = 0; i<length; i++) {
		fprintf(fp, "%.2f\n", y[i]);	
	}
	fclose(fp);
	return 0;
}

int main()
{
	const char* filePath = "test.txt";
	double a[10] = { 0,1.0,2,3,4,5,6,7,8,9 };
	int length = 10;
	saveDataToTXT(a, length, filePath);

	system("pause");
    return 0;
}

保存到bin文件

#include "stdlib.h"
#include<stdio.h>

int saveDataToBin(int y[], int length, const char* filePath) {
	int i = 0, j = 0;										
	FILE *fpwrite;
	fpwrite = fopen(filePath, "wb"); //数据导出
	if (fpwrite == NULL)
	{
		printf("cant open the file fpwrite");
		exit(0);
	}
	
	int nwrite = 0;
	nwrite = fwrite(y, sizeof(int), length, fpwrite);
	if (nwrite == 0 && filePath != NULL) {
		printf("write failed!");
	}
	fclose(fpwrite);

	return 0;
}

int main()
{
	const char* filePath = "test.bin";
	int a[10] = { 0,1,2,3,4,5,6,7,8,9 };
	int length = 10;
	saveDataToBin(a, length, filePath);

	system("pause");
    return 0;
}

1.2 c语言读文件

读txt文件,读bin文件

#include "stdlib.h"
#include<stdio.h>

//读bin文件
void read_bin(const char *path, int *buf, int size)  
{  
    FILE *infile;  
      
    if((infile=fopen(path,"rb"))==NULL)  
    {  
        printf( "\nCan not open the path: %s \n", path);  
        exit(-1);  
    }  
    fread(buf, sizeof(int), size, infile);
    fclose(infile);  
} 

//读txt文件
int readTXT(const char *filePath, int buf[], int length)
{
	FILE *fpRead = fopen(filePath, "rb"); //读数据
	if(fpRead == NULL)
	{
		printf("cant open the file fpRead");
		exit(0);
	}

	
	for(int i = 0; i < length; i++)
	{
		fscanf(fpRead,"%d ", &buf[i]);	
		printf("%d\n",buf[i]);		
	}
	return 0;
}

int main()
{
	int i=0;
	const char* filePath = "test.bin";
	int a[10] = { 1,1,2,3,4,5,6,7,8,9 };
	int b[10];
	int length = 10;
	//saveDataToTXT(a, length, filePath);
	//readTXT(filePath, b, length);

	saveDataToBin(a, length, filePath);
	read_bin(filePath, b, 10);
	for (i = 0; i < 10; i++)
	{
		printf("b[%d]=%d\n", i, b[i]);
	}
	
	system("pause");
    return 0;
}

2 c++读写文件

参考:C++ 文件和流 | 菜鸟教程

程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放,通过文件可以将数据持久化,C++中对文件操作需要包含头文件 < fstream >

文件类型分为两种:

  1. 文本文件 - 文件以文本的ASCII码形式存储在计算机中

  2. 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们

操作文件的三大类:

  1. ofstream:写操作

  2. ifstream: 读操作

  3. fstream : 读写操作

2.1 文本文件

2.1.1 写文件

写文件步骤如下:

  1. 包含头文件

    #include <fstream>

  2. 创建流对象

    ofstream ofs;

  3. 打开文件

    ofs.open("文件路径",打开方式);

  4. 写数据

    ofs << "写入的数据";

  5. 关闭文件

    ofs.close();

文件打开方式:

打开方式解释
ios::in为读文件而打开文件
ios::out为写文件而打开文件
ios::ate初始位置:文件尾
ios::app追加方式写文件
ios::trunc如果文件存在先删除,再创建
ios::binary二进制方式

注意: 文件打开方式可以配合使用,利用|操作符

例如:用二进制方式写文件 ios::binary | ios:: out

#include <fstream>

void test01()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out);

	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	ofs << "年龄:18" << endl;

	ofs.close();
}

int main() {

	test01();

	system("pause");

	return 0;
}

2.1.2 读文件

读文件步骤如下:

  1. 包含头文件

    #include <fstream>

  2. 创建流对象

    ifstream ifs;

  3. 打开文件并判断文件是否打开成功

    ifs.open("文件路径",打开方式);

  4. 读数据

    四种方式读取

  5. 关闭文件

    ifs.close();

#include <fstream>
#include <string>
void test01()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in);

	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}

	//第一种方式
	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}

	//第二种
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf,sizeof(buf)))
	//{
	//	cout << buf << endl;
	//}

	//第三种
	//string buf;
	//while (getline(ifs, buf))
	//{
	//	cout << buf << endl;
	//}

	char c;
	while ((c = ifs.get()) != EOF)
	{
		cout << c;
	}
	ifs.close();


}

int main() {
	test01();
	system("pause");
	return 0;
}

  

2.2 二进制文件,bin文件

以二进制的方式对文件进行读写操作

打开方式要指定为 ==ios::binary==

2.2.1 写文件

二进制方式写文件主要利用流对象调用成员函数write

函数原型 :ostream& write(const char * buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

#include <fstream>
#include <string>

class Person
{
public:
	char m_Name[64];
	int m_Age;
};

//二进制文件  写文件
void test01()
{
	//1、包含头文件
	//2、创建输出流对象
	ofstream ofs("person.txt", ios::out | ios::binary);

	//3、打开文件
	//ofs.open("person.txt", ios::out | ios::binary);

	Person p = {"张三"  , 18};
	//4、写文件
	ofs.write((const char *)&p, sizeof(p));

	//5、关闭文件
	ofs.close();
}

int main() {
	test01();
	system("pause");
	return 0;
}

2.2.2 读文件

二进制方式读文件主要利用流对象调用成员函数read

函数原型:istream& read(char *buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

#include <fstream>
#include <string>

class Person
{
public:
	char m_Name[64];
	int m_Age;
};

void test01()
{
	ifstream ifs("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
	}

	Person p;
	ifs.read((char *)&p, sizeof(p));

	cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}

int main() {
	test01();
	system("pause");
	return 0;
}

3 MATLAB读写文件

3.1 MATLAB读文件

读bin文件

bin文件存储方式:
   big endian:  大尾端,也称大端(高位)优先存储。
   little endian:小尾端,也称小端(低位)优先存储。
   如下00000000 00000000 00000000 00000001的存储
   大尾端: 00000000 00000000 00000000 00000001
                  addr+0      addr+1      addr+2      addr+3    //先存高有效位(在低地址),即低地址存高位
   小尾端: 00000001 00000000 00000000 00000000
                   addr+0     addr+1      addr+2      addr+3    //先存低有效位(在低地址),即低地址存低位
fid  = fopen('rx_data.bin');

if fid==-1
    fprintf('file open error!\n');
    return;
end

//加入bin文件中存放的数据类型是int16
data = fread(fid, 900, 'int16');//读取900个int16数据,
//data = fread(fid, 'int16'); //一次性读取
//data = fread(fid, 'int32', 'ieee-be');//小尾端读

 读txt文件

data=load('data.txt');

3.2 MATLAB写文件

输出到txt文件

fid = fopen('char.txt','a+'); 
for i=1:10
    fprintf(fid,'%.2f\n',data(i));
end

fprintf(fid,'-----------------------------------------------\n'); 

fclose(fid);

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在C++读写MATLAB的MAT文件,可以使用MATLAB C++ API。这个API可以让你在你的C++程序中调用MATLAB引擎,并且使用MATLAB引擎来读写MAT文件。下面是一些基本的步骤: 1. 安装MATLAB引擎API,这通常可以在MATLAB的安装目录下找到。 2. 在你的C++程序中包含MATLAB引擎API的头文件。 3. 创建MATLAB引擎对象并启动它。 4. 使用MATLAB引擎对象来读取MAT文件中的数据。 5. 使用MATLAB引擎对象来写入数据到MAT文件中。 下面是一些示例代码,可以帮助你开始使用MATLAB引擎API: ```c++ #include "mat.h" #include "engine.h" #include <iostream> int main() { // 启动MATLAB引擎 Engine* eng = engOpen(NULL); if (!eng) { std::cout << "无法启动MATLAB引擎" << std::endl; return 1; } // 读取MAT文件中的变量 mxArray* data = matGetVariable(eng, "filename.mat", "variablename"); if (!data) { std::cout << "无法读取MAT文件中的变量" << std::endl; return 1; } // 使用变量 // ... // 写入数据到MAT文件中 matPutVariable(eng, "filename.mat", "variablename", data); // 释放资源 mxDestroyArray(data); engClose(eng); return 0; } ``` 在这个示例中,我们启动了MATLAB引擎,然后使用`matGetVariable`函数来读取MAT文件中的变量。我们可以使用返回的`mxArray`对象来访问这个变量的数据。然后,我们使用`matPutVariable`函数将修改后的变量写入MAT文件中。最后,我们释放了使用的资源,并关闭MATLAB引擎。 注意,这只是一个简单的示例,实际情况下可能需要更多的代码来处理错误和异常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值