ccodeblocksfopenfclose

How to open/close a file in a function in an endless loop


My problem is that I get the "too many files open" (Process returned 1 (0x1) ) error and I don't know why. I close the file with fclose() every time. I do that in a function and this function is in an endless loop. The content of the file is 0;71;0;

#include <stdio.h>
#include <stdlib.h>

void myfunction(){
    char buffer[20];
    char *r = NULL;
    char *g = NULL;
    char *b = NULL;

    FILE *s = fopen("settings.txt", "rb");
    if (!s) { perror("fopen1"); exit(EXIT_FAILURE); }
    if(s != NULL){

        fgets(buffer,sizeof(buffer),s);
        r = strtok(buffer,";");
        g = strtok(NULL,";");
        b = strtok(NULL,";");
    }
    fclose(s);
}
int main(){

   for(;;){
       myfunction();
   }

   return 0;
}

Solution

  • A debugger attached to your IDE might be remembering the files and not closing them, rather than your program being at fault!

    Running the program directly in a terminal might highlight this issue - if indeed that's the case, you might consider submitting a report to them along with your test program and/or strace the IDE itself to find the issue yourself.