Jesus
Jesus

Reputation: 15

How to do a loop time stamp function for a file created with fopen in C?

I would like to insert the date in 3 different file names with a time stamp function doing a loop. I already have a working time stamp function but how I do it to loop? I tried passing an argument to the function but is not working.

Thats what i have:

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

const char* time_stamp(int i)
{
time_t rawtime;
struct tm * timeinfo;
static char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
char file_name[3][50] = {"name1.txt", "name2.txt", "name3.txt"};
strftime (buffer,80,file_name[i],timeinfo);

return buffer;
}

int main ()
{

int i = 0;
for (i = 0; i < 3; i++) 
 {

  const char * (*filename_ptr)();
  filename_ptr = &time_stamp();


  FILE * fp;
  fp = fopen(filename_ptr(), "w+");
  if( !fp )
     return 1;
  fprintf(fp, "%s", output.buffer);
  fclose( fp );

  if( output.buffer )
  {
    free ( output.buffer );
    output.buffer = 0;
    output.size = 0;
  }
 }

}

Whitout the "int i" argument it works fine but only prints one name. How can I do the loop work?

Upvotes: 0

Views: 76

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409472

When you do

filename_ptr = &time_stamp();

you call the time_stamp function with no argument, and take a pointer to the returned string.

If you want a pointer to the function (why?) then drop the parentheses.

Later you use the pointer to the function (which doesn't point to a function) and call it, again without an argument.

All of this should cause the compiler to should loudly at you, and lead to plenty of undefined behavior.

Furthermore there is no output variable, which will lead to a compiler error.

By the way, the time_stamp function doesn't really do anything with the time. It basically only copies a fixed static string into the buffer.


To call the function in a loop, just do it? Passing the loop iterator variable as argument.

for (int i = 0; i < 3; ++i)
{
    FILE *fp = fopen(time_stamp(i));
    ...
}

Upvotes: 2

Related Questions