gpt4 book ai didi

c - 将函数指针作为参数传递给 fopen

转载 作者:行者123 更新时间:2023-11-30 18:28:50 25 4
gpt4 key购买 nike

我创建了一个小型 C 程序来创建时间戳并将其附加到文件文本名称中:

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

void time_stamp(){
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);

strftime (buffer,80,"myFile_%F.txt",timeinfo);
printf ("%s", buffer);
}


int main ()
{
void (*filename_ptr)();
filename_ptr = &time_stamp;

FILE * fp;

fp = fopen (filename_ptr, "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

fclose(fp);

return 0;
}

但是我无法让 fopen 接受指向创建带有时间戳的名称的函数的指针。它需要一个 const char。我如何将函数指针转换到它?

最佳答案

fopen() 需要一个 const char * 作为第一个参数:

FILE *fopen(const char *path, const char *mode);

在您的函数 time_stamp() 中,您打印时间戳并且不返回任何内容,即:void

<小时/>

您的新 time_stamp() 函数可以改为(注意 buffer 声明中的 static):

const char* time_stamp(){
time_t rawtime;
struct tm * timeinfo;
static char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);

strftime (buffer,80,"myFile_%F.txt",timeinfo);
return buffer;
}

然后您可以在调用 fopen()调用这个新函数。 time_stamp() 返回的值将变成 fopen() 的第一个参数:

const char * (*filename_ptr)();
filename_ptr = &time_stamp;
// ...
fp = fopen (filename_ptr(), "w+");

请注意,从 time_stamp() 返回的值的类型现在与 fopen() 期望的第一个参数的类型匹配(即:const char *)。

<小时/>

线程安全注意事项

由于函数 time_stamp() 包含静态分配的存储(缓冲区),因此在多线程中使用此函数是不安全的程序,因为调用此函数的所有线程将共享此存储的单个实例。

关于c - 将函数指针作为参数传递给 fopen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44404831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com