9 years, 2 months ago.

question about the filename

could you solve this kind problem, if i want to create 100 txt file, thus i need to put the code into a for loop. while the file name should be different, if all are text.txt, there will certainly be only one txt file.

Question relating to:

Demo program showing the LocalFileSystem in use file, Local, System

1 Answer

9 years, 2 months ago.

The following code will open 100 text files and store their FILE pointers in an array. If it fails to open any of the files it will stop trying and return the number of files it did open.

If you only need the files one at a time it would make more sense to only have one file pointer and a counter to keep track of the current file number. You could then open and close the files as needed.

Either way the basic idea is to use sprintf to create a string with a changing file name. This is the same as printf used for text output only it stores the result in a character array. snprintf is a version of sprintf where it also checks you don't overflow the maximum output size.

In the file name I used %03d, this formats the number as being 3 digits with leading 0's so that the files names are text000.txt, text001.txt etc... rather than text0.txt. This means that as long as you have less than 1000 files they will show up in the correct order when you sort the directory by file name.

// number of files to open
#define k_NumberOfFiles 100

// file pointers
FILE *FileHandles[k_NumberOfFiles];

// creates the files, returns the number opened.
int createFiles() {

  char fname[24]; // array to hold the filename.
  
  for (int i = 0; 1 < k_NumberOfFiles; i++) { // for each file
    snprintf(fname,24,"/local/text%03d.txt",i);   // create the file name
    FileHandles[i] = fopen(fname, "w");             // open the file
    if (!FileHandles)                                             // check it opened OK
     return i;   
  }

  return k_NumberOfFiles;
}