1
votes

I want to call a function which creates files periodically on every 5 seconds in C. The function code is below which creates files.

void file_create(int time) {
        snprintf(filename, sizeof(filename),"%s_%d", "data", index);
        FILE *fp = fopen (filename, "w");
        index++;
}

file name will be data_0, data_1, data_2 and goes on on every call.

how to call the above function periodically every 5 seconds from main function if i put an infinite loop like below

while(1){
    file_create();
    Sleep(5000);
}

this is not allowing to execute the lines below the while loop.

How to achieve this by calling above function periodically without holding execution of rest of the program ?

2
Did you think about using a separate thread or does it have to be in the same thread?Gerhardh
Are you aware of timerfd_create ?Gerhardh
@Milag Uppercase means Windows and Microsoft's C lib plus Windows API. Glibc won't be available.Lundin
Everyone says multithreading but you can also use an event loop. Which are also large topics. Look up libuv.Qix - MONICA WAS MISTREATED
Please mark the posting with some windows tag.Milag

2 Answers

0
votes

You are looking for a multithread system. You have to create one task which executes the mentioned while loop and another one which executes the other parts of your current programm.

0
votes

You do this with multi-threading, which is a big topic by itself. I'd recommend to study how POSIX threads (pthreads) work before anything else.

In Windows, that means that the thread should waiting for a custom event "close the thread" for 5000ms. If you get the event, stop the thread. Otherwise in case of timeout, perform the periodic task. Windows uses a different thread API than POSIX.

And also different Sleep(ms) (Windows) vs sleep(s) (POSIX) functions...