How to create multiple . txt files?

Asked

Viewed 1,787 times

1

How do I create multiple . txt files in c/c++ ? I have that function:

tocopy(){
    FILE *file = fopen("Teste.txt", "w");
    fclose(file);
}

But it only creates a Test.txt file

  • 2

    C or C++? Different languages with different solutions of their own.

  • 2

    To create different files you must call fopen with different filenames.... Please explain your problem better so we can give a more satisfactory answer.

1 answer

4


In C, you can, for example, loop in which you generate different filenames. If you always create a file with the same name, the Operating System will only save the latest file.

#include <stdio.h>
#include <stdlib.h>

void tocopy(void) {
    int k;
    for (k = 0; k < 100; k++) {
        char filename[100];
        FILE *file;
        sprintf(filename, "Teste-%02d.txt", k); /* Teste-00.txt; Teste-01.txt; ...; Teste-99.txt */
        file = fopen(filename, "w");
        if (file != NULL) {
            fclose(file);
        } else {
            perror(filename);
            exit(EXIT_FAILURE);
        }
    }
}
  • 3

    I think it’s great when someone just answers the question! and objectively! For those beginners who have trouble formulating questions we thank!!! , Thank you @pmg!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.