how can i write to more than one text file using a single fwrite?

1 view (last 30 days)
i am writing a code in which the result of each iteration of for loop is to be written to different text files.how can i do it?please help..
  3 Comments
PRIYA
PRIYA on 23 Feb 2013
Edited: PRIYA on 23 Feb 2013
In my code,i have to open my input text file, extract some strings from it and write to a text file.Again i extract some other strings and write it to another text file.like that i have to write to many text files depending on the text content.so i need a loop in which write operation is done to multiple files.i got problems with fid in the loop when using fwrite.please help..

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 17 Feb 2013
You can't. Each file will require its own file handle (ID). And each fwrite() or fprintf() can take only one file handle at a time. So that means you will need multiple calls to fwrite() or fprintf(). Why did you want a single fwrite() anyway?

More Answers (1)

Walter Roberson
Walter Roberson on 17 Feb 2013
As Image Analyst notes, each file will require its own file handle. However, file handles are numeric and so can be stored in an array. Therefore, provided your operating system supports enough simultaneously open files, you could open all of the files in advance, storing the fids into an array, and then index that array in the writing loop in order to write into different files. Remember to close the files afterwards.
Older MS Windows operating systems were frequently limited to 64 simultaneously open files (MATLAB uses at least 4 of its own.) Even now it is not uncommon to encounter MS Windows systems limited to 255 simultaneously open files (i.e., 251 user files after the 4 MATLAB uses.) Linux systems might support 1024 out of the box, depending which release. Linux and OS-X should be configurable for more simultaneously open files.
I am not recommending this approach for most situations; the few cases where it is genuinely useful are much more likely to be written in C or C++.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!