利用MATLAB&C语言生成&读取.dat文件

本文介绍了如何在MATLAB和C语言环境下读写.dat文件。MATLAB中,使用fopen和fprintf/fscanf进行文件操作,C语言同样借助fopen和fprintf/fscanf实现。读取时注意文件路径和格式匹配,确保数据正确写入和读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


有时候,需要在matlab或c语言编程环境中写入或读取.dat文件,一种可行的方式如下:


MATLAB生成.dat文件

testdata = 0 : 10;
fp_w = fopen('data.dat', 'wt');
fprintf(fp_w, '%d\n', testdata);

MATLAB读取.dat文件

方式一
fp_r = fopen('data.dat', 'rt');
testdata = fscanf(fp_r, '%d')
方式二
testdata = load('data.dat')

C语言生成.dat文件

#include "stdio.h"
int main(void)
{
	int testdata[10];
	int i;
	for(i = 0; i < 10; i++)
	{
		testdata[i] = i;
	}
	FILE * fp_r = fopen("data.dat", "wt");
	for(i = 0; i < 10; i++)
	{
		fprintf(fp_r, "%d\n", testdata[i]);
	} 
	return 0;
}

C语言读取.dat文件

#include "stdio.h"
int main(void)
{
	int testdata[10];
	int i;
	FILE * fp_r = fopen("data.dat", "rt");
	for(i = 0; i < 10; i++)
	{
		fscanf(fp_r, "%d", &testdata[i]);
	}
	//测试输出
	for(i = 0; i < 10; i++)
	{
		printf("%d\n", testdata[i]);
	}
	return 0;
}

注意事项

  1. 在读取.dat文件时,如果使用相对路径,需要将.dat文件放在与程序同一子目录的文件下内,否则,需要使用绝对路径。

  2. 注意写入格式以及读取格式。

  3. 参数含义
    wt以文本形式写入
    rt以文本形式读入
    wb以二进制形式写入
    rb以二进制形式读入
MATLAB读取.dat文件有两种方式。方式一是使用fscanf函数,代码如下: ```matlab fp_r = fopen(&#39;data.dat&#39;, &#39;rt&#39;); testdata = fscanf(fp_r, &#39;%d&#39;); ``` 方式二是使用load函数,代码如下: ```matlab testdata = load(&#39;data.dat&#39;); ``` 请注意,在使用fscanf函数时,需要指定读取的数据类型,如上述代码中的&#39;%d&#39;表示读取整数。而使用load函数时,它会自动根据文件中的数据类型进行读取。 另外,为了确保读取文件路径正确,可以使用addpath函数添加路径。例如: ```matlab path = &#39;E:\201508&#39;; addpath(path); ``` 这样就可以在MATLAB读取指定路径下的.dat文件了。 #### 引用[.reference_title] - *1* [利用MATLAB&amp;C语言生成&amp;读取.dat文件](https://blog.csdn.net/Differoucius/article/details/121598005)[target=&quot;_blank&quot; data-report-click={&quot;spm&quot;:&quot;1018.2226.3001.9630&quot;,&quot;extra&quot;:{&quot;utm_source&quot;:&quot;vip_chatgpt_common_search_pc_result&quot;,&quot;utm_medium&quot;:&quot;distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt&quot;}} ] [.reference_item] - *2* *3* [MATLAB读取Argo数据【3】--一次性读取所有的dat文件的Argo信息](https://blog.csdn.net/m0_59346120/article/details/125734181)[target=&quot;_blank&quot; data-report-click={&quot;spm&quot;:&quot;1018.2226.3001.9630&quot;,&quot;extra&quot;:{&quot;utm_source&quot;:&quot;vip_chatgpt_common_search_pc_result&quot;,&quot;utm_medium&quot;:&quot;distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt&quot;}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

creature0001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值