Read File Line by Line and Count in Matlab;save in one string

143 views Asked by At

How do i read this file line by line & count the length ? Please help.

numDim: 4
dim: 128 128 128 1
fov: 26.88 26.88 26.88  1.000
interval: 0.21 0.21 0.21 1.0
dataType: word
sdtOrient: ax
endian: ieee-le
1

There are 1 answers

1
il_raffa On

If you just want to:

  • read the file line by line
  • store each line in a string
  • count the numnber of lines and the length of each line

you can use the functions:

  • fopen to open the file
  • fgetl to read (within a loop) each line
  • length to evaluate the length of each line
  • fclose to close the input file at the end

you should also use a counter to count the number of lines.

To store the line you can use a cellarray

This is a possible implementation:

% Open the input file
fp=fopen('input_txt_file.txt','r');
% Initialize a counter
cnt=0;
% Read the input file line by line
while 1
   % Read the line
   tline = fgetl(fp);
   % Check for the end of file
   if ~ischar(tline)
      break
   end
   % Increment the counter once a line has been read
   cnt=cnt+1
   % Store the line in a cellarray
   str_cell{cnt}=tline
   % Get the length of the string
   str_len(cnt)=length(tline)
end
% Close the input file
fclose(fp);

In case you want to read the input file and store the "numeric" values in an array, in addition to the above mentioned functions you can use:

  • strtok` to scan the line

you can then use a struct to save the input; this allows you to dynamically create the fild of the struct assigning them, as name, the first string of each line.

A switch can be used to identify the specific line and scan the data accordingly.

A possible impleentation can be:

% Open the input file
fp=fopen('input_txt_file.txt','r');
% Initialize a counter
cnt=0;
% Read the input file line by line
while 1
   % Read the line
   tline = fgetl(fp);
   % Check for the end of file
   if ~ischar(tline)
      break
   end
   % Increment the counter once a line has been read
   cnt=cnt+1
   % Scan the line
   [token, remain]=strtok(tline,' ')
   % Store the data in a struct
   switch(token)
      case 'numDim:'
         data_struct.(token(1:end-1))=str2num(remain)
      case 'dim:'
         data_struct.(token(1:end-1))=str2num(remain)
      case 'fov:'
         data_struct.(token(1:end-1))=str2num(remain)
      case 'interval:'
         data_struct.(token(1:end-1))=str2num(remain)
      case 'dataType:'
         data_struct.(token(1:end-1))=remain(2:end)
      case 'sdtOrient:'
         data_struct.(token(1:end-1))=remain(2:end)
      case 'endian:'
         data_struct.(token(1:end-1))=remain(2:end)
   end

end
% Close the input file
fclose(fp);

This create the following output struct:

data_struct = 

       numDim: 4
          dim: [128 128 128 1]
          fov: [26.8800 26.8800 26.8800 1]
     interval: [0.2100 0.2100 0.2100 1]
     dataType: 'word'
    sdtOrient: 'ax'
       endian: 'ieee-le'

Hope this helps,

Qapla'