Home > Back-end >  How to create efficient function in C for handling multiple arguments to be formatted in char array
How to create efficient function in C for handling multiple arguments to be formatted in char array

Time:12-16

Lets say I wanted to construct a string with many different values from a struct in C to build a SQL query.

The python way to handle string formatting could be:

str = "INSERT INTO main.post VALUES('{0}', '{1}');".format('title', 'Some random text here...')

print(str)

Result after print(str):

INSERT INTO main.post VALUES('title', 'Some random text here...');

Current code:

I'm using a typedef for defining my structure. Then initializing it with these values:

typedef struct {
  char              title[50];
  char              text[5000];
} post_t;

post_t post = {
     {
         "title",
         "Some random text here..."
     }
};
    

Is there some clever way I can do this in C? I will have a lot of different SQL queries so it might be good to create some sort of util function for handling it.

CodePudding user response:

You can use snprintf() to do that:

post_t post = {"Title", "Some random text here..."};
char query[1024];
snprintf(query, sizeof(query), "INSERT INTO main.post VALUES('%s', '%s');", post.title, post.text);
    
printf("%s\n", query);

Output:

INSERT INTO main.post VALUES('Title', 'Some random text here...');

But as @user253751 pointed out, this code is very prone to SQL Injection attacks. You will have to use prepared statements to prevent that.

Here are some C APIs for some database providers:

  •  Tags:  
  • c
  • Related