A blog to help electrical engineers and students to learn electrical engineering topics. Basic Electrical Engineering, Power Systems, Electrical Machines, tec.. Now special course on MATLAB for Beginners.

Class

Class

Saturday, June 11, 2016

Working with Files in MATLAB - Part 3

fwrite( ) - Write binary data to file

fwrite function is used to  write the elements of matrix A to the specified file. The data are written in column order. After write action the pointer will be set to the end of the file.
Count = fwrite(FID, A, ’precision’) format the elements of matrix A to the specified data type defined by precision and write to the file specified by FID.
The optional argument ‘precision’ is similar to the fread function. It defines the format and size of the data written to the file. The default data type is ‘unit8’.
Example:
The following example open the file test.txt and write the data stored in the variables X, Y and Z in the previous example in to it.
>> fileID = fopen('test.txt','wt');
>> fwrite(fileID,X,'char');
>> fwrite(fileID,Y,'char');
>> fwrite(fileID,Z,'char');

Both fread and fwrite functions include another optional argument SKIP, that specifies the number of bytes to skip before the read or write action. If the SKIP argument is present, the fwrite function skips some data and writes a value, skips and writes another value, etc. until all of A is written.


fgets( ) and fgetl( ) - Read a line of data from the file

Both the functions read a complete line of data from a file. The difference is in the way they store the end of line/ new line characters like \n ,\r etc.
fgets - keep the newline characters
fgetl - discard the newline characters
Both A = fgets(FID)  or A= fgetl(FID) read a full line of data in a file defined by FID and saves the data in to the variable A. If just an end-of-file is encountered then -1 is returned. If an error occurs while reading, the function returns an empty string.
Example:
>> fileID = fopen('test.txt','rt');
>> A =fgets(fileID)
A =
Welcome to Electrical
>> A =fgets(fileID)
A =
Engineering
>> A =fgets(fileID)
A =
Tutorial
The difference between fgets and fgetl can be understood only with the files that contain newline characters. If there is no new line character, both functions will give same result. Given a file with no newline characters, fgets may take a long time to execute.
Example:
If there is an end of line character ‘\n’ after the first line of the previous example, the result of both functions are given below:
>> A =fgets(fileID)
A =
Welcome to Electrical\n
>> A =fgets(fileID)
A =
Welcome to Electrical
submit to reddit

0 comments:

Post a Comment