From this question here, What's the best way to check if a file exists in C? (cross platform), the best solution seems to use the access()
function found in the unistd.h
header.
#include <string.h>
#include <stdio.h>
#include <unistd.h>
const size_t MAX_FILENAME_LENGTH = 12;
const int MAX_FILENAME_TRIES = 1000;
char *get_next_filename()
{
char *filename = malloc(MAX_FILENAME_LENGTH);
FILE *file;
int found = 0, i = 0;
do {
snprintf(filename, "game%d.txt");
if (access(filename, F_OK) < 0) { //if file does not exist, we've found our name!
found = 1;
} else {
++i;
}
} while (! found && i < MAX_FILENAMES_TRIES);
return filename;
}
The code here returns the next available filename as a C string, starting from game0.txt
up to gameN.txt, where N is the value of MAX_FILENAME_TRIES. Don't forget to free()
the file name once you've used it.