Question

I want to create a folder called ‘all’ and after that I want to create and write many text files in ‘all’. The name of the text files being x1.txt, x2.txt, x3.txt & so on. Here is my approach but it fails somehow:

    folderName  = all;       
    mkdir(folderName);

    temp = ['x', num2str(k), '.txt'];
    fid2 = fopen('x.txt', 'w');
    fprintf(fid2, '%s\n', [folderName/temp '/' M{:}]); % M is a string, that I want to write in the text file
    fclose(fid2);
Was it helpful?

Solution

Try this -

folderName = 'all';
mkdir(strcat(folderName,filesep,'temp'));

N = 10; %%// Number of files needed
for k = 1:N
    temp = ['x', num2str(k), '.txt'];
    pathname1 = strcat(pwd,filesep,folderName,filesep,'temp',filesep,temp);%%// creates the temp directory in the working directory.

    fid1 = fopen(pathname1, 'w');
    fprintf(fid1, '%s\n',M{:});
    fclose(fid1);

end

Thus, the files x1.txt, x2.txt, x3.txt and so on would be created inside the directory temp that is inside a directory all and all is inside the working directory.

If you would like to create this directory all elsewhere, mention the full path for folderName at the start and edit the pathname1 creation, like this -

pathname1 = strcat(folderName,filesep,'temp',filesep,temp);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top