How can I create multiple files in a loop in Go?

Hello everyone, first time asking for help as I haven’t found an answer to this anywhere and my attempts all result in errors. I’m writing a simulation and I need it to automatically create data files such as “results-1.dat”, “results-2.dat”, “results-3.dat” and so on. I read that this is possible in C (Create multiple files in C automatically - Stack Overflow), but I haven’t been able to replicate it in Go, be it with Sprintf or os.Create (os.Create doesn’t allow one to write something like “(“results%d.dat”, i)”, it seems).

Here’s the C code from the link above. Is a similar structure (loop) possible in Go? If not, how can I automatically create these files?
“FILE *files[numfiles];
for (int i = 0; i < numfiles; i++)
{
char filename[20];
sprintf(filename, “results%d.dat”, i);
files[i] = fopen(filename, “w”);
}”

Many thanks in advance!

Here’s a slightly updated version of that written in Go:

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	numFiles := 5
	for i := 0; i < numFiles; i++ {
		fileName := fmt.Sprintf("results-%v.dat", i)
		file, err := os.Create(fileName)
		if err != nil {
			log.Fatalf("Problem creating file: %v", err)
		}
		fmt.Fprintf(file, "The contents of %v", fileName)
		file.Close()
	}
}

I’m writing content to the file just so the compiler won’t complain about that unused variable. Also normally you see a lot of defer file.Close() but in the case where you’re running this in a loop you want to more aggressively close your files because you can reach the OS max open files pretty quickly. Anyway, hope this helps!

2 Likes

Hi! Your answer was really helpful and I was able to solve my problem! Thank you!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.