Home > Net >  check if function was called before
check if function was called before

Time:11-05

Here is my basic code that I'm trying to work with.

void test(){
    FILE *input;
    input = fopen("input.txt.", "r");
}

So I'm trying to check if file was already opened before, meaning that void test() function was called once before. I realy have no idea how to do that, i tried it with while and if. Like this.

void test(){
    FILE *input;
    int open = 0;
    while (open == 0){
        input = fopen("input.txt", "r");
        if (input == NULL){
            printf("File wasnt opened.\n");
        }
        if (input != NULL){
            printf("File is opened.\n");
        }
        open = open   1;
    }
    if(open!=0){
        printf("file is already opened.\n");
    }
}

CodePudding user response:

Use a local static variable.

void test (void)
{
  static bool called_before = false;

  if(called_before)
  {
    do_this();
  }
  else
  {
    do_that();
    called_before = true;
  }
}

CodePudding user response:

Supposing that your intent is for test to open the file just once but to read from the file each time it is called, you can make input static:

void test(void)
{
    /*  Since input is static, it will be initialized with NULL when the
        program starts and we will retain its value between calls to
        the function.
    */
    static FILE *input = NULL;

    //  If input has not been set for an open file yet, try to open it.
    if (!input)
    {
        input = fopen("input.txt", "r");
        if (!input)
        {
            fprintf(stderr, "Error, unable to open input.txt.\n");
            exit(EXIT_FAILURE);
        }
    }

    for (int c = fgetc(input); c != EOF && c != '\n'; c = fgetc(input))
        putchar(c);
    putchar('\n');
}

Note static objects should generally be avoided, as they complicate program state and so may lead to more bugs. It is okay to play with them in student programs to learn how they work, but their use in real-world applications should be limited.

  •  Tags:  
  • c
  • Related