(转)matlab中fprintf, fscanf, fwrite, fread函数的用法

标签:
matlab函数 |
分类: MATLAB及信号分析 |
fwrite写的是二进制内容,fprintf写的是数字转换成ASCII码之后的字符。两者都把数字64写入一个文件,用记事本打开看下,fwrite写的打开是乱码,fprintf写入的是6和4这两个字符。因为fwrite写的是64的二进制表示(4个字节,前面全是0,最后八位是0100000),fprintf写入的实际内容是36H和34H(16进制表示的字符6和字符4的ASCII编码)
fwrite(&v,sizeof(int),1,f);//文件中被写四个字节0x01 0x00 0x00 0x00(32位int,小端存储)
fprintf(f,"%d",v);//文件中被写一个字节0x31(即'1'的ASCII码)
又比如
int v=0x12345678;
fwrite(&v,sizeof(int),1,f);//文件中被写四个字节0x78 0x56 0x34 0x12(32位int,小端存储)
fprintf(f,"%x",v);//文件中被写八个字节0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38
fprintf(f,"%d",v);//文件中被写九个字节0x33 0x30 0x35 0x34 0x31 0x39 0x38 0x39 0x36
(因为0x12345678==305419896)
-
clear
-
clc
-
-
cd('C:\Documents
and Settings\Administrator\桌面\matlab\test'); -
-
a
= 1 : 10; -
fid
= fopen('myData.txt', 'w'); -
fprintf(fid,
'%d ', a); -
fclose(fid);
1 2 3 4 5 6 7 8 9 10
-
clear
-
clc
-
-
cd('C:\Documents
and Settings\Administrator\桌面\matlab\test'); -
-
fid
= fopen('myData.txt', 'r'); -
[a
count] = fscanf(fid, '%d', inf); -
fclose(fid);
-
clear
-
clc
-
-
cd('C:\Documents
and Settings\Administrator\桌面\matlab\test'); -
-
a
= 0 : 255; -
fid
= fopen('myFile.yuv', 'wb'); -
fwrite(fid,
a, 'uchar'); -
fclose(fid);
-
clear
-
clc
-
-
cd('C:\Documents
and Settings\Administrator\桌面\matlab\test'); -
-
fid
= fopen('myFile.yuv', 'rb'); -
[a
count] = fread(fid, inf, 'uchar'); -
fclose(fid);
-
clear
-
clc
-
-
cd('C:\Documents
and Settings\Administrator\桌面\matlab\test'); -
-
fid
= fopen('myData.txt', 'r'); -
[a
count1] = fscanf(fid, '%d', [5 2]); -
fclose(fid);
-
-
fid
= fopen('myFile.yuv', 'rb'); -
[b
count2] = fread(fid, [16 16], 'uchar'); -
fclose(fid);
a =
b =