【问题标题】:snprintf function not declared?snprintf 函数未声明?
【发布时间】:2018-10-27 10:47:11
【问题描述】:

我正在尝试使用 snprintf 函数,该函数基于我已阅读的手册是 <stdio.h> 标头的一部分,但是我收到一个错误,它已被隐式声明。这是我的代码:

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

struct users {
    char* user_id;
};
    typedef struct users users_t;

int save_user_detail(user_t);

int main() {
    users_t users;
    save_user_detail(users);
    return 0;
}

int save_user_detail(users_t users)
{

    printf("Type the filename = ");
    scanf("%s", users.user_id);
    char* extension = ".txt";
    char fileSpec[strlen(users.user_id)+strlen(extension)+1];
    FILE *file;
    snprintf(fileSpec, sizeof(fileSpec), "%s%s", users.user_id, extension);
    file = fopen(fileSpec, "w");
    if(file==NULL) 
    {
        printf("Error: can't open file.\n");
        return 1;
    }
    else 
    {
        printf("File written successfully.\n");
        fprintf(file, "WORKS!\r\n");
    }
    fclose(file);
    return 0;
 }

【问题讨论】:

    标签: c printf stdio


    【解决方案1】:

    你好像在使用gcc,但是这个编译器不一定使用glibc,它符合C标准并且支持snprintf

    在 Windows 架构上,您可能正在使用 Microsoft C 库,在旧版本中没有 snprintf 或将其重命名为 _snprintf

    您可以通过以下 2 种方法尝试解决您的问题:

    • 尝试使用_snprintf 而不是snprintf
    • 在包含&lt;stdio.h&gt; 后手动定义snprintf

      int snprintf(char *buf, size_t size, const char *fmt, ...);
      

    编译器应该停止抱怨缺少原型,并且如果运行时库确实有 snprintf 的符号和匹配的调用约定,它将链接到它并且程序应该按预期运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多