How to Read Text File Backwards Using MATLAB?
Last Updated :
23 Sep, 2022
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
fp = fopen( 'test.txt' , 'r' );
fseek(fp,0, 'eof' );
size = ftell(fp);
M = char(zeros([1 size]));
n = 1;
fseek(fp,-1, 'cof' );
c = fread(fp,1, '*char' );
M(1,n) = c;
while (fseek(fp, -2, 'cof' ) ~= -1)
n = n + 1;
c = fread(fp, 1, '*char' );
M(1,n) = c;
end
fclose(fp);
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.
Share your thoughts in the comments
Please Login to comment...