Matlab 读写文件

来源:互联网 发布:机械工艺设计软件 编辑:程序博客网 时间:2024/06/15 16:52
一、读取文本文件
思路:
1、用fopen来打开一个文件句柄
2、用fgetl来获得文件中的一行,如果文件已经结束,fgetl会返回-1
3、用fclose来关闭文件句柄

比如,read.txt的内容如下:

0.1 0.1 151.031 -12.3144 -29.0245 3.112850.1 0.2 120.232 -2.53284 -8.40095 3.33480.1 0.3 136.481 -0.33173 -22.4462 3.5980.1 0.4 184.16 -18.2706 -54.0658 2.516960.1 0.5 140.445 -6.99704 -21.2255 2.42020.1 0.6 127.981 0.319132 -29.8315 3.113170.1 0.7 106.174 -0.398859 -39.5156 3.974380.1 0.8 105.867 -20.1589 -13.4927 11.64880.1 0.9 117.294 -11.8907 -25.5828 4.971910.1 1 79.457 -1.42722 -140.482 0.7264930.1 1.1 94.2203 -2.31433 -11.9207 4.71119


那么可以用下面的代码来读取该文本文件:

fid=fopen('read.txt','r');data=[];while 1    tline=fgetl(fid);%读取一行    if ~ischar(tline),break;    end %if与end是一对标记    tline=str2num(tline);%字符串转化为数字    data=[data;tline];%将tline存取数组enddata;%显示数据fclose(fid);



这样文本文件中的内容就读入到了data中了。
二、写入文本文件
思路:

1、用fopen打开一个文件句柄,但要用“w+”或“r+”等修饰符,具体参看help fopen

'r'

Open file for reading.

'w'

Open or create new file for writing. Discard existing contents, if any.

'a'

Open or create new file for writing. Append data to the end of the file.

'r+'

Open file for reading and writing.

'w+'

Open or create new file for reading and writing. Discard existing contents, if any.

'a+'

Open or create new file for reading and writing. Append data to the end of the file.

'A'

Open file for appending without automatic flushing of the current output buffer.

'W'

Open file for writing without automatic flushing of the current output buffer.



2、用fprintf写入数据
3、用fclose来关闭文件句柄

比如下面的程序:


fid=fopen('write.txt','a+');fprintf(fid,'Hello,world\r\n');a=rand(1,10);fprintf(fid,'%g\r\n',a);fclose(fid);
运行程序,就会生成write.txt

Hello,world0.1576130.9705930.9571670.4853760.800280.1418860.4217610.9157360.7922070.959492

所以,用MATLAB来进行操作文本文件是不是很简单啊。

原创粉丝点击