Search code examples
cprintfstdio

snprintf function not declared?


I'm trying to use the snprintf function which based on the manual I've read is apart of the <stdio.h> header however I'm getting an error that it's been implicitly declared. Here is my code:

#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;
 }

Error


Solution

  • You seem to be using gcc, but this compiler does not necessarily use the glibc, which is compliant with the C Standard and supports snprintf.

    On the Windows architecture, you may be using the Microsoft C library, which in older versions did not have snprintf or renamed it as _snprintf.

    Here are 2 ways you can try a work around your problem:

    • try using _snprintf instead of snprintf.
    • define snprintf manually after including <stdio.h> as

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

    The compiler should stop complaining about the missing prototype and if the runtime library does have a symbol for snprintf with a matching calling convention, it will link to it and the program should behave as expected.