开发者

Add string to char array in C

I have a C array called buf. Here is it's definition:

char buf[1024];

Now, my current code takes from stdin and uses fgets() to set that array, however I wish to use code to set it instead. Right now the line that sets buf looks like this:

fgets(buf, 1024, stdin);

Basically, I want to replace stdin, with say... "开发者_如何学GoMy String". What's the best way to do this?


Look for sprintf, for example here: Cpp reference

Edit:

sprintf(buf, "My string with args %d", (long) my_double_variable);

Edit 2:

As suggested to avoid overflow (but this one is standard C) you can use snprintf.


snprintf is only C99 not C89, sprintf_s/strcpy_s are only MSVC, not C89, not C99.

char *mystr="come from stdin or file or ...";
char buf[1024];
...
memset(buf,0,sizeof buf);
strncpy(buf,mystr,(sizeof buf)-1);

or non array:

#define BUFLEN 512
char *mystr="come from stdin or file or ...";
char *buf;
...
char *buf=calloc(1,BUFLEN);
strncpy(buf,mystr,BUFLEN-1);

It works on all ANSI C environments.


strcpy(buf, "My String");

Microsoft's compiler also include a function strcpy_s, which is a "safe" version of strcpy. It makes sure that you won't overrun buf. In this particular case, that's probably not a problem, but you shoul dknow about. But, be aware, it's not available with any other compiler, so it can;t be used where portable is needed.

 strcpy_s(buf, sizeof(buf), "My String");


There are many variants, some have been already proposed, some not:

...

char input[] = "My String";

strcpy(buf, input);

strncpy(buf, input, sizeof(buf));

sscanf(input, "%s", buf);

sprintf(buf, "%s", input);

memcpy(buf, input, strlen(input));

...

most of them are unsure/insecure. What exactly should be taken depends on what you really want to do in your code.

Regards

rbo


Verbose but safe:

int copy_size = sizeof( buf ) - 1 < strlen( MyString ) ? sizeof( buf ) - 1 : strlen( MyString );
memset( buf, 0, copy_size + 1 );
memcpy( buf, MyString, copy_size );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜