在Matlab中逐行读取文件;保存在一个字符串中

时间:2016-12-27 05:13:12

标签: arrays string matlab readfile string-length

我如何逐行阅读此文件&算长吗?请帮忙。

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName.Equals("CompleteTransaction"))
        {                
           int rowIndex = Convert.ToInt32(e.CommandArgument); // Get the current row 

            GridViewRow row = GridView1.Rows[index];
            Label lblName = (Label)row.FindControl("lblName")
            DropDownList drpList= (DropDownList)row.FindControl("ddlServiceType");
            lblName.Text = drpList.SelectedValue;             
        }
    }

1 个答案:

答案 0 :(得分:0)

如果您只想:

  • 逐行阅读文件
  • 将每一行存储在一个字符串中
  • 计算行的数量和每行的长度

你可以使用这些功能:

  • fopen打开文件
  • fgetl读取(在循环内)每行
  • length评估每行的长度
  • fclose最后关闭输入文件

您还应该使用计数器来计算行数。

要存储该行,您可以使用cellarray

这是一种可能的实施方式:

% 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);

如果您想要读取输入文件并将“数字”值存储在数组中,除了上述功能外,您还可以使用:

  • strtok`扫描线

然后您可以使用结构来保存输入;这允许你动态创建结构的fild,作为名称,分配每行的第一个字符串。

switch可用于识别特定行并相应地扫描数据。

可能的实施可能是:

% 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);

这将创建以下输出结构:

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'

希望这有帮助,

Qapla'