0

我希望有人可以帮助我,如何实现这一目标。我有一个将排列写入文件的代码。我意识到我的输出文件很大。我想知道如何能够在每次写入多行时拆分更改文本的名称,f.eks,每写入 1000 行更改文件的名称。任何帮助将不胜感激。

到目前为止我的代码:

fid = fopen( 'file1.txt' );
cac = textscan( fid, '%20s' );
fclose( fid );
num = cac{1};
fid = fopen( 'file2.txt' );
cac = textscan( fid, '%20s' );
fclose( fid );
str = cac{1};
fid = fopen( 'file3.txt', 'w' );
for ii = 1 : length( num )
    for jj = 1 : length( str )
        fprintf( fid, '%1s - %1s\n', num{ii}, str{jj} );
    end
end   
fclose( fid );
4

1 回答 1

1

这个想法是检测何时写入 1000 行,关闭文件,生成新文件名,打开新文件并继续。

我对 MATLAB 有点生疏,但应该是这样的:

fid = fopen( 'file1.txt' );
cac = textscan( fid, '%20s' );
fclose( fid );
num = cac{1};
fid = fopen( 'file2.txt' );
cac = textscan( fid, '%20s' );
fclose( fid );
str = cac{1};
fileCounter = 1; % Count the number of files we have used
lineCounter = 0; % Count the number of lines written to the current file
filename = sprintf('out_file%u.txt', fileCounter); % generate a filename, named 'out_file1.txt', 'out_file2.txt', etc.
fid = fopen( filename, 'w' );
for ii = 1 : length( num )
  for jj = 1 : length( str )
    fprintf( fid, '%1s - %1s\n', num{ii}, str{jj} );
    lineCounter++; % We have written one line, increment the lineCounter for the current file by one
    if (lineCounter == 1000) then % if we have written 1000 lines:
      fclose( fid ); % close the current file
      fileCounter++; % increase the file counter for the next filename
      filename = sprintf('out_file%u.txt', fileCounter); % generate the filename
      fid = fopen( filename, 'w' ); % open this new file, 'fid' will now point to that new file
      lineCounter = 0; % reset the line counter, we have not written anything to the file yet
    end_if
  end
end
fclose( fid );

注意:我写了这个,这个代码没有经过测试。

于 2014-11-11T09:05:47.140 回答