Open In App

How to Read Text File Backwards Using MATLAB?

Last Updated : 23 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites: Write Data to Text Files in MATLAB

Sometimes for some specific use case, it is required for us to read the file backward. i.e. The file should be read from EOF (End of file Marker) to the beginning of the file in reverse order. In this article we would learn how to read a file in backward using MATLAB. For demonstration we would be using a file named test.txt with the following contents:

 

Example 1:

Matlab




% MATLAB program for read text file %
  
% Open the file
  fp = fopen('test.txt', 'r');
  
% Move the file pointer to EOF
 fseek(fp,0,'eof');
  
% Get the position of File Pointer
 size = ftell(fp);
  
% Creating a 1d array of size = fsz
 M = char(zeros([1 size]));
 n = 1;
  
% Move one position backward from EOF
 fseek(fp,-1,'cof');
  
% Reading the bytes (as char) 
% at that location
 c = fread(fp,1,'*char');
  
% Storing the character as the 
% first element of the Matrix
  M(1,n) = c;
  
% A Loop that continues until 
% the Start of file is reached
    while(fseek(fp, -2, 'cof') ~= -1)
      
    % Statement below are for reading 
    % the character, moving the pointer
    % and storing the character in 
    % the matrix continually
        n = n + 1;
        c = fread(fp, 1, '*char');
        M(1,n) = c;
    end
  
 fclose(fp);
  
% Displaying the Matrix
 display(M);


Output:

 

Code Explanation:

Firstly, we opened our file named test.txt using fopen function in read mode. Then we moved the file reading pointer from 0 (start of file) to end of file. Then we used ftell to tell the position where the pointer is currently located (bytes from start to EOF). Now, we used the value obtained from the previous step to allocate a Sparse matrix of the same size as the value. 

We would be storing the characters from the file inside that matrix. After which the pointer within the file was moved 1 step back, from its current position (at EOF), Which is the position of the last byte of the file. Then we read that byte and store it as an character, and later append it to the predefined empty matrix. Then we enter a loop from where we continually do the last 2 steps until we reach the start of file, at which fseek function will return a value of -1 and the loop will end. In the end we display the Matrix we populated from the previous code, containing byte of the file in reverse order. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads