Hari Sankar v m
Hari Sankar v m

Reputation: 193

How to use ***sprintf_s*** for linux C++

I am trying a Create a Linux C++ project using the same header and .cpp files from a Windows C++ project using Visual Studio. I am using sprintf_s to convert string to array.

But when I port the same code to Linux, sprintf_s is showing error. Is there any other replacement for sprintf_s?

Is that ok to use snprintf instead of sprintf_s ?

#if _WINDLL
        sprintf_s(DestinationArray, SourceString.c_str()); //Syntax using sprintf_s for Windows
#else

        snprintf(DestinationArray, SourceString.length(), SourceString.c_str()); //syntax using snprintf For Linux

#endif

Is the above syntax correct? I am new to C++ . Please help.

Upvotes: 3

Views: 11061

Answers (3)

justcodin
justcodin

Reputation: 1012

I use this macro for linux :

#define sprintf_s(buffer, ...) snprintf((buffer), __VA_ARGS__)

Upvotes: 0

eerorika
eerorika

Reputation: 238401

Is there any other replacement for sprintf_s?

There is std::snprintf. Even better, you could use std::string and iostreams.

Is that ok to use snprintf instead of sprintf_s ?

std::snprintf is a replacement for sprintf_s. However, Passing the source string size as the second argument is wrong. You're supposed to pass the size of the destination buffer instead.

Furthermore, you're misusing sprintf_s in the first place. You should never use non-constant format string. It appears that you're attempting to simple copy a string. For that purpose, there is for example strlcpy (not standard in C++, but exists in BSD and Linux).

Upvotes: 2

Botje
Botje

Reputation: 30937

sprintf_s passes the size of DestinationArray, not SourceString. Also, don't pass arbitrary strings as format string, that's how you get format string exploits.

A more correct formulation:

#if _WINDLL
        sprintf_s(DestinationArray, "%s", SourceString.c_str()); //Syntax using sprintf_s for Windows
#else
        snprintf(DestinationArray, sizeof(DestinationArray), "%s",  SourceString.c_str()); //syntax using snprintf For Linux
#endif

Or you can define sprintf_s for Linux as a macro:

#define sprintf_s(buf, ...) snprintf((buf), sizeof(buf), __VA_ARGS__)

Upvotes: 1

Related Questions