Dienstag, 9. Oktober 2012

Read words in a file in reverse order


Consider a file that contains the following text,
            Brand New World
The result after reading the words in the reverse order
         World New Brand





Steps to be performed:
1.      Open a file and move the pointer to the end of the file.
2.      Move the pointer to the current-1 position
3.      Read the character and store it in an array.
4.      Move the pointer to the current-2 position and read the character and store it in an array.
5.      If the character is a blank space, then reverse the array. To reverse array use 'fliplr'.
6.      Append the array to a string and initialize the array to zero.
7.      Repeat this procedure till the pointer reaches the beginning of the file.




MATLAB CODE:

%Open a file to read
fp=fopen('rev.txt');

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

%Find the position
fsz=ftell(fp);

n=1;
%Move the pointer to the current-1 position
fseek(fp,-1,'cof');

%Read a character
c=fread(fp,1,'*char');

%Store in the matrix
M(1,n)=c;
Words=0;

%Check whether the file pointer has reached the beginning of the file
    while(fseek(fp,-2,'cof')~=-1)
       
        c=fread(fp,1,'*char');
        %When a space is encountered reverse the character array and append
        %it to a string
        if(isspace(c))
              if(Words==0)
                  %Intially, the string is empty.
                  %Append the array in the reverse order with a blank space
                   Words=[fliplr(M) blanks(1)];
              else
                  %Append the reversed character array to the string
                   Words=[Words fliplr(M)];
              end
           n=1;
           M='';
        else
            %The array is updated with the characters until blank space is
            %encountered
           n=n+1;
           M(1,n)=c;
          
        end


    end
   
Words=[Words fliplr(M)];
display(Words);

fclose(fp);








Result:

Words =

World New Brand