一、读取文本文件 思路: 1、用fopen来打开一个文件句柄 2、用fgetl来获得文件中的一行,如果文件已经结束,fgetl会返回-1 3、用fclose来关闭文件句柄
比如,read.txt的内容如下:
0.1 0.1 151.031 -12.3144 -29.0245 3.11285
0.1 0.2 120.232 -2.53284 -8.40095 3.3348
0.1 0.3 136.481 -0.33173 -22.4462 3.598
0.1 0.4 184.16 -18.2706 -54.0658 2.51696
0.1 0.5 140.445 -6.99704 -21.2255 2.4202
0.1 0.6 127.981 0.319132 -29.8315 3.11317
0.1 0.7 106.174 -0.398859 -39.5156 3.97438
0.1 0.8 105.867 -20.1589 -13.4927 11.6488
0.1 0.9 117.294 -11.8907 -25.5828 4.97191
0.1 1 79.457 -1.42722 -140.482 0.726493
0.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存取数组
end
data;%显示数据
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,world
0.157613
0.970593
0.957167
0.485376
0.80028
0.141886
0.421761
0.915736
0.792207
0.959492
所以,用MATLAB来进行操作文本文件是不是很简单啊。