Search code examples
matlabloopsreadfilewritefile

Changing file name, when fprintf reaches an N number of lines


i hope someone can help me, how to achieve this. I have a code that writes permutation to a file. i realized that my output file is very big. i would like to know how to be able to split change the name of the text when a number of lines has been written every time, f.eks, changing the name of the file every written 1000 lines. any help will be appreciated.

my code so far :

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

Solution

  • The idea is to detect when 1000 lines have been written, close the file, generate a new filename, open the new file and continue.

    I'm a bit rusty in MATLAB, but it should be something like this:

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

    Note: I wrote this out of my head, this code is not tested.