90 likes | 201 Vues
Low-level Input/Output. The load command does not always succeed in reading an input file. It only works when all lines in the file have the same ASCII format. Files with header material do not qualify, nor do binary files.
E N D
Low-level Input/Output • The load command does not always succeed in reading an input file. It only works when all lines in the file have the same ASCII format. Files with header material do not qualify, nor do binary files. • ASCII files that cannot be input with the loadfunction can be opened and input with MATLAB functions that are similar to C language functions. The MATLAB functions include fopen, fgets, fscanf, and sscanf.
Low-level I/O Use to read files in any format • fopen: open a file • fclose: close a file • fread, fscanf: read from a file • fwrite,fprintf: write to a file • fgetl: read a line from file
fopen Open a file and returns a file id reference to that file, returns -1 if file can’t be opened file_id = fopen(filename,permissions) - filename - name of the file to open - permissions - mode in which the file will be opened • ‘r’ - open file for reading • ‘w’ - writing • ‘a’ – append to existing file etc • Examples: To open a file for input is: infile_id = fopen('filename','r'); • The command to open a file for output is: outfile_id = fopen('filename','w');
fclose • Close an open file status= fclose(file_id) • Status is 0 if the file was successfully closed, and -1 otherwise
fprintf / fscanf • fprintf: write formatted data to a file fprintf(fid,format,val1,val2,....) • Example: fid = fopen('mydata.dat','wt'); fprintf(fid,'%f\n',pi); fprintf(fid,'%s\t%s\n',’hello’,’goodbye’); fclose(fid); • fscanf: read formatted data from a file array = fscanf(fid,format) • Example: fid = fopen('mydata.dat', 'rt'); p = fscanf(fid,'%f‘,1) h = fscanf(fid,’%s’,1) g = fscanf(fid,’%s’,1) fclose(fid);
Write data example % open file fid = fopen('myfile.txt','wt'); % 'wt' means "write text" if (fid < 0) error('could not open file "myfile.txt"'); end; % write some stuff to file for i=1:100 fprintf(fid,'%3d\t%6d\n',i,i*i); end; % close the file fclose(fid);
Read data example % open file fid = fopen('myfile.txt','rt'); % 'rt' means "read text" if (fid < 0) error('could not open file "myfile.txt"'); end; % read from file into table with 2 rows and 1 column per line tab = fscanf(fid,'%d %d\n',[2,inf]); % close the file fclose(fid);
Exercises • Write a program to generate a table containing the sine and cosine of θ between 0o and 90o in 1o increments. Use a for loop and the fprintf function. The program should correctly label each of the columns in the table. • Write a program to read these numbers back into an n x 3 matrix using the fscanf function.