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 に答える