How to Read Text File Backwards Using MATLAB?


In MATLAB, reading a text file backwards involves reversing the order of the lines written in the file. We can use MATLAB to reverse the order and read the text file backwards. For this, MATLAB provides various methods using different functions and algorithms. In this tutorial, I will explain the commonly used methods to read a text file backward using MATLAB.

Create a Text File in MATLAB

In MATLAB, we can create a text file using the built-in functions "fopen" and "fprintf".

Example

The following example demonstrates the process of creating a text in MATLAB.

% MATLAB code to create a text file
% Open a text file in writing mode
file_id = fopen('TextFile.txt', 'w');

% Check whether the file is opened successfully
if file_id == -1
   fprintf('Unable to open or create the file.');
   return;
end

% Specify the content to be written to the text file
content = "Tutorials Point is an e-Learning platform designed to provide high-quality content on various subjects.";
content = [content, "You can learn from video tutorials."];
content = [content, "You can learn from text tutorials."];

% Write the content to the text file
fprintf(file_id, '%s
', content); % Close the text file fclose(file_id); % Display a confirmation message fprintf(' The "TextFile.txt" has been created successfully.');

Output

The "TextFile.txt" has been created successfully.

Content −

Tutorials Point is an e-Learning platform designed to provide high-quality content on various subjects.
You can learn from video tutorials.
You can learn from text tutorials.

Let us now discuss different methods of reading the text file backwards using MATLAB.

Method 1: Read Text File Backwards Character by Character

This method involves the following steps to read the text file backward −

  • Step (1) − Open your text file in read mode. For this use the "fopen" function with ‘r’ parameter.

  • Step (2) − Create an empty string to store the reversed text.

  • Step (3) − Determine the total file size by moving the file pointer to the end of the file. For this, use the "fseek" function with "eof", where "eof" stands for "end of the file".

  • Step (4) − Determine the total file size of the text file in bytes using the "ftell" function.

  • Step (5) − Iterate a loop through the content of the file to read it in backward direction.

  • Step (6) − Close the file to free up the system resources.

  • Step (7) − Display the result.

This is all about algorithm used in this method of reading a text file backward in MATLAB.

Example

Let us see an example to understand the code implementation for algorithm.

% MATLAB code to read a text file backward
% Open the text file in read mode
file_id = fopen('TextFile.txt', 'r');

% Check whether the file is opened successfully
if file_id == -1
   fprintf('Unable to open the text file.');
   return;
end

% Create an empty string to store the backward text
back_text = '';

% Move the file pointer to end of the text file
fseek(file_id, 0, 'eof');

% Determine the total file size
file_size = ftell(file_id);

% Iterate a loop to read the characters in the file in backward direction
for p = file_size : -1 : 1		% Determine current position of file pointer
   fseek(file_id, p, 'bof');	% Move the file pointer to current position
   c = fread(file_id, 1, 'char');	% Read the character at current position
   back_text = [back_text, c];	% Store the character in the backward text
end

% Close the text file
fclose(file_id);

% Display the backward text
disp(back_text);

Output

.slairotut txet morf nrael nac uoY
.slairotut oediv morf nrael nac uoY
.stcejbus suoirav no tnetnoc ytilauq-hgih edivorp ot dengised mroftalp gninraeL-e na si tnioP slairotu

Explanation

From the output, it can be seen that in this method we have read the text file backward. In this method, the file is read backward character by character.

Let us discuss another method of reading a text file backward in MATLAB.

Method 2: Read Text File Backwards Line by Line

The steps to be followed in this method to read a text file backward in MATLAB are explained below.

  • Step (1) − Open the text file using the "fopen" function with "r" mode.

  • Step (2) − Check if the file is opened successfully.

  • Step (3) − Create an empty cell array to store the lines of text in backward order.

  • Step (4) − Define a loop to read the lines of text in the file and store them in the cell array in backward order.

  • Step (5) − Close the text file using the "fclose" function.

  • Step (6) − Display the text of each line in backward order.

Example

Let us see an example to implement these steps for reading a text file backward.

% MATLAB code to read a text file backwards
% Open the text file in read mode
file_id = fopen('TextFile.txt', 'r');

% Check whether the file is opened successfully
if file_id == -1
   fprintf('Unable to open the file.');
   return;
end

% Create an empty cell array to store lines of text in backward order
back_lines = {};

% Define a loop to read text lines in the file and store in the cell array
while true
      l = fgetl(file_id);	% Read the current text line
    
   % Break the loop if we have reached end of the file
   if ~ischar(l)
      break;
   end
    
   % Store the line to the cell array in backward order
   back_lines = [l; back_lines];
end

% Close the text file
fclose(file_id);

% Display the lines in backward order
for i = 1 : length(back_lines)
   disp(back_lines{i});
end

Output

You can learn from text tutorials.
You can learn from video tutorials.
Tutorials Point is an e-Learning platform designed to provide high-quality content on various subjects.

Explanation

It is clear that the algorithm used in this method reads the text file backwards line by line.

Conclusion

In this tutorial, I have explained two simplest methods to read a text file in backward order using MATLAB. Reading a text file backwards is sometimes crucial in specific applications. We can use MATLAB to read a text file backwards. I demonstrated the step-by-step process with the help of example to read a text file backwards using MATLAB.

The first method reads the text file backwards character by character, while the second method reads the text file backwards line by line. You can try these methods with your own text files.

Updated on: 06-Oct-2023

52 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements