Search code examples
cfilesequencefopenfclose

How to create create a text files sequence in C


I want to create text files sequence like...

student1.txt
student2.txt
student3.txt
...

How to do it?

I have a sample code, but its not working for my problem.

#include<stdio.h>

void main()
{
    FILE *fp;
    int index;

    for(index=1; index<4; index++)
    {
        fp=fopen("student[index].txt","w");
        fclose(fp);
    }
}

Solution

  • You are using a a fixed string "student[index].txt" rather than making a string with the number you want in it.

    void main()
    {
      FILE *fp;
      int index;
      char fname[100];
    
      for(index=1; index<4; index++)
      {
        sprintf(fname, "student%d.txt", index);
        fp=fopen(fname,"w");
        fclose(fp);
      }
    }