i would like to print all the content from the files in the same folder. The attached photo shows how i named my files. i would first random generate a sequence according to fisher yates shuffle and then print the files according to the sequence.
however, in my program, i keep getting buffer overflow detected and could only print the content of the first file. i have tested and the overflow occurs after the while loop and before the rewind(pic)
statement. it works when i print one single file, so it shouldn't be the problem with the arrays 'folder1' and 'folder2'. i think the main problem is with the 'loadPhoto' function, but i still provided other parts of the code (necessary ones) for your reference.
also i added this to test which part is wrong,
printf("first test");
rewind(pic);
printf("\n");
printf("second test");
however, the weird thing is when printf("\n");
is added in the third row, 'first test' can be printed. however, when printf("\n");
is deleted, 'first test' cannot be printed.
int i, j;
FILE *pic;
FILE *correctAns;
char ch;
char category[10] = "";
int secondTries = 3, correct;
char askCategory() {
printf("\nAnimals Weather\n");
printf("Clothes Food\n");
printf(" Fruit Jobs\n");
printf("\nWhich category of vocabulary would you like to learn? ");
scanf("%s", category);
}
void fisherYatesShuffle(int arr[]){
int random, temp;
srand(time(NULL));
for (i=14; i>0; i--){
random = rand()%(i+1);
temp = arr[i];
arr[i] = arr[random];
arr[random] = temp;
}
}
void loadPhoto(){
char photo[3];
int sequence[15];
for (i=0; i<15; i++)
sequence[i] = i;
fisherYatesShuffle(sequence);
char folder1[20] = "ascii_art/";
char folder2[10] = "";
strcat(strcpy(folder2, category), "/");
for(i=0; i<15;i++){
sprintf(photo, "%d", sequence[i]);
pic = fopen(strcat(strcat(folder1, folder2), photo), "r");
if (pic == NULL)
printf("Error. Cannot open the file.");
printf("\n");
while ((ch = fgetc(pic)) != EOF){
printf("%c", ch);
}
printf("first test");
rewind(pic);
printf("\n");
printf("second test");
rewind(pic);
printf("\n");
}
}
void Level1() {
askCategory();
// printf("%s", category);
loadPhoto();
}
int main(void) {
int form = 0, level;
do {
printf("Enter your level of study (1-6): ");
scanf("%d", &form);
if (form == 1 || form == 2 || form == 3)
Level1();
else if (form == 4 || form == 5 || form == 6)
Level2();
else
printf("Invalid input. Please input again.\n");
} while (form < 1 || form > 6);
return 0;
}
here is my code. i have tried using the rewind function but it doesnt solve the problem. thank you very much for your help!!!