MATLAB – Read Words in a File in Reverse Order
Last Updated :
22 Aug, 2022
MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It allows matrix manipulations, plotting of functions, implementation of algorithms, and creation of user interfaces
Suppose we are given a text file containing the following words “I STUDY FROM GEEKS FOR GEEKS”. Now, if we want to read the words of the file in the reverse order, the outcome should be “GEEKS FOR GEEKS FROM STUDY I”.
Algorithm:
- Open the given file using fopen() function (This function takes the name of the file as its argument and returns a pointer to a FILE structure type that can be used to access the open file).
- Jump the returned pointer to the end of the given text file using fseek() function
- Now, shift that pointer to the end-1 position.
- Read the character to which the pointer is pointing using fread() function and store it in a matrix.
- Next, shift the pointer to the current-2 position, again read the character to which the pointer is pointing, and store it in a matrix.
- Now, If the character is a blank space, then reverse the array. Use fliplr() to reverse the array/
- Then, append the array to a string and initialize the array to zero.
- Replicate this algorithm till the pointer fp reaches the starting of the file.
- Close the file using fclose() function.
Example 1:
Matlab
fp=fopen( 'rev.txt' );
fseek(fp,0, 'eof' );
fsz=ftell(fp);
i=1;
fseek(fp,-1, 'cof' );
chr=fread(fp,1, '*char' );
Z(1,i)=chr;
Word=0;
while (fseek(fp,-2, 'cof' )~=-1)
c=fread(fp,1, '*char' );
if (isspace(chr))
if (Word==0)
Word=[fliplr(Z) blanks(1)];
else
Word=[Words fliplr(Z)];
end
i=1;
Z= '' ;
else
i=i+1;
Z(1,i)=chr;
end
end
Word=[Word fliplr(Z)];
display(Word);
fclose(fp);
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...