I am working on a text adventure game in C which has become the bane of my existence. I'm working through it and making progress, however, I'm having one big problem that I can't seem to figure out.
Here's the deal: I need to create 7 files and then print the information about each room in each file.
An example of one file would be:
ROOM NAME: Chapel
CONNECTION 1: Arenas
CONNECTION 2: Pantry
CONNECTION 3: Forest
ROOM TYPE: START_ROOM
Each file should have a different name, different connections, and a different type. However, when I run my program, it prints the exact same thing in every file.
My program is pretty long so I'm not sure where the issue is, so I'll just write where I create the files and call the function to write into it--if you guys need to see more let me know. This is also just portions of the main and createRoom() function.
int main() {
int buffer = 260;
int pid = getpid();
char *dirName = malloc(buffer);
char *prefix = "bonnc.rooms.";
snprintf(dirName, buffer, "%s%d", prefix, pid);
struct stat st = {0};
if (stat(dirName, &st) == -1) {
mkdir(dirName, 0777);
}
char rm1[260];
snprintf(rm1, 260, "%s/room1.txt", dirName);
roomFile1 = fopen(rm1, "w+");
createRoom(roomFile1, connections1, 1);
char rm2[260];
snprintf(rm2, 260, "%s/room2.txt", dirName);
roomFile2 = fopen(rm2, "w+");
createRoom(roomFile2, connections2, 2);
fclose(roomFile1);
fclose(roomFile2);
}
void createRoom(FILE *fp, char *conn[6], int roomNumber) {
srand(time(NULL));
int randName = rand() % 10;
int randType = rand() % 3;
int randConnections = rand() % (6 -2) +2;
int j = 0;
for (j = 0; j <= randConnections; j++) { //I do have additional code in here for testing of duplicates, but that isn't essential to the problem
randomRoom = rand () % 10;
conn[j] = names[randomRoom];
}
fprintf(fp, "ROOM NAME: %s\n", names[randName]); //names & randName are declared earlier
int t = 0;
for (t = 0; t <= randConnections; t++) { //randConnections defined earlier
fprintf(fp, "CONNECTION %d: %s\n", t+1, conn[t]; //conn[t] defined earlier
}
fprintf(fp, "ROOM TYPE: %s\n", types[randType]); //types & randType defined earlier
}
So when I call createRoom with room1 and room2, the exact same things are printed in each file, even though a new random name, random connections, and random type should be generated each time the createRoom function is called.
Any ideas? I'm new to C and still learning, so if there's any messy code that I should change, let me know. Thank you!
Update: the random numbers aren't global, they are in the createRoom() function. I added this code, as well as a portion of how connections[1] & connections[2] are populated. Hopefully this information helps clear things up!