It's probably best to initially read each of the files into arrays. Then you can randomly print the names from the arrays.
Code:
// rnd_names.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAXNAMES 100
#define MAXNAMELEN 50
#define NAMES_FILE "names.txt"
#define SURNAMES_FILE "surnames.txt"
int read_file(const char *filename, char arr[][MAXNAMELEN]) {
int size = 0;
FILE *file = fopen(filename, "r");
char line[MAXNAMELEN];
while (fgets(line, sizeof line, file)) {
line[strcspn(line, "\n")] = '\0'; // remove newline
strcpy(arr[size++], line);
}
fclose(file);
return size;
}
int rnd(int n) {
return rand() % n; // int from 0 to n - 1
}
int main() {
srand(time(0)); // seed random number generator with current time
char names[MAXNAMES][MAXNAMELEN];
int nam_len = read_file(NAMES_FILE, names);
char surnames[MAXNAMES][MAXNAMELEN];
int sur_len = read_file(SURNAMES_FILE, surnames);
char ch;
do {
printf("%s %s\n", names[rnd(nam_len)], surnames[rnd(sur_len)]);
printf("Again (y/n)? ");
} while (scanf(" %c", &ch) == 1 && (ch == 'y' || ch == 'Y'));
return 0;
}