你不能,但你可以通过追加()
的指针调用该函数。对于这项工作,改变你的函数实际上返回const char *
(或char *
)
注意你不能只返回一个指针到您buffer
,因为这是一个局部变量不再存在时,函数返回。您可以从函数外部传递指向buffer
的指针。然后,您的原型应该是
char *time_stamp(char *buf, size_t len);
修改后的代码:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
char *time_stamp(char *buf, size_t len){
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buf,len,"myFile_%F.txt",timeinfo);
return buf;
}
int main()
{
char *(*filename_ptr)(char *, size_t);
filename_ptr = &time_stamp;
char buffer[80];
FILE * fp;
fp = fopen (filename_ptr(buffer, 80), "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);
fclose(fp);
return 0;
}
有其他方法如何设计这个功能。 Neroku当你确定你永远不需要线程上下文中的函数时,答案是很好的。它简化了使用,甚至还有一些标准的C库函数。
第三种方法是通过从malloc()
中获取它来使缓冲区成为分配的对象。这具有线程安全并且不需要任何额外参数的优点,函数本身像在原始的破碎版本中一样控制缓冲区的大小。缺点是调用者必须使用free()
这个内存。这个示例代码(我这里不推荐的):
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
char *time_stamp(){
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
char *buf = malloc(80);
strftime (buf,80,"myFile_%F.txt",timeinfo);
return buf;
}
int main()
{
char *(*filename_ptr)();
filename_ptr = &time_stamp;
FILE * fp;
char *filename = filename_ptr();
fp = fopen (filename, "w+");
free(filename);
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);
fclose(fp);
return 0;
}
你期望fopen如何处理函数指针? – Yunnosch
这是因为你的CPU没有DWIM(我的意思是什么)指令。在此之前,你需要实际告诉计算机该做什么,因为它无法读懂你的想法。 – Art
查看您的手册或手册页,了解fopen的原型。这是你需要履行的合同。这些是你必须遵守的规则。如果有一个'const char *'作为第一个参数,那么你不应该传入一些奇怪的奇特函数指针。 – Gerhardh