Home > database >  Create 1000 data.txt files using a loop in C
Create 1000 data.txt files using a loop in C

Time:01-23

I want to use a loop that creates 1000 files named like data1.txt, data2.txt, data3.txt,...data1000.txt. But unfortuantely, we can't pass a number separately to fopen(). I must only create one file at a time.

CodePudding user response:

Try:

#include <stdio.h>

int main()
{
    char name[] = "data";
    char ext[] = ".txt";
    int num_files = 1000;

    //   12 because of 11 digits of int, one null character
    char current_name[strlen(name)   strlen(ext)   12] = {};
    for (int i = 1; i <= num_files; i  ) {
        sprintf(current_name, "%s%d%s", name, i, ext);
        // FILE *f = fopen(current_name, "rw");
        // fclose(f);
    }
    return 0;
}

Commenting out the fopen() since I really do not want anyone to paste this and break their system. I know this won't do anything since we are not writing any data, but I don't like it uncommented.

  •  Tags:  
  • Related