C语言 如何使用sprintf附加字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2674312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append strings using sprintf?
提问by user46646
I am facing a serious issue with sprintf.
我正面临 sprintf 的严重问题。
Suppose my code snippet is:
假设我的代码片段是:
sprintf(Buffer,"Hello World");
sprintf(Buffer,"Good Morning");
sprintf(Buffer,"Good Afternoon");
.
.
.
Some hundred sprints....
几百个冲刺....
If I do like this, its getting overwritten.
如果我喜欢这个,它就会被覆盖。
How can I avoid overwritting using sprintf. If I give a printf at the end I want to see all the lines.
如何避免使用 sprintf 覆盖。如果我最后给出 printf 我想看到所有的行。
回答by
You need:
你需要:
sprintf(Buffer,"Hello World");
sprintf(Buffer + strlen(Buffer),"Good Morning");
sprintf(Buffer + strlen(Buffer),"Good Afternoon");
and of course you need your buffer to be big enough.
当然你需要你的缓冲区足够大。
回答by Matthew T. Staebler
int length = 0;
length += sprintf(Buffer+length, "Hello World");
length += sprintf(Buffer+length, "Good Morning");
length += sprintf(Buffer+length, "Good Afternoon");
Here is a version with some resistance to errors. It is useful if you do not care when errors happen so long as you can continue along your merry way when they do.
这是一个对错误有一定抵抗力的版本。如果您不在乎错误何时发生,只要您能在错误发生时继续快乐地前进,它就会很有用。
int bytes_added( int result_of_sprintf )
{
return (result_of_sprintf > 0) ? result_of_sprintf : 0;
}
int length = 0;
length += bytes_added(sprintf(Buffer+length, "Hello World"));
length += bytes_added(sprintf(Buffer+length, "Good Morning"));
length += bytes_added(sprintf(Buffer+length, "Good Afternoon"));
回答by Oleg Razgulyaev
For safety (buffer overflow) I recommend to use snprintf()
为了安全(缓冲区溢出),我建议使用 snprintf()
const int MAX_BUF = 1000; char* Buffer = malloc(MAX_BUF); int length = 0; length += snprintf(Buffer+length, MAX_BUF-length, "Hello World"); length += snprintf(Buffer+length, MAX_BUF-length, "Good Morning"); length += snprintf(Buffer+length, MAX_BUF-length, "Good Afternoon");
回答by Michael Burr
A snprintfcat()wrapper for snprintf():
一个snprintfcat()包装为snprintf():
size_t
snprintfcat(
char* buf,
size_t bufSize,
char const* fmt,
...)
{
size_t result;
va_list args;
size_t len = strnlen( buf, bufSize);
va_start( args, fmt);
result = vsnprintf( buf + len, bufSize - len, fmt, args);
va_end( args);
return result + len;
}
回答by Jeegar Patel
Use the return value of sprintf()
使用返回值 sprintf()
Buffer += sprintf(Buffer,"Hello World");
Buffer += sprintf(Buffer,"Good Morning");
Buffer += sprintf(Buffer,"Good Afternoon");
回答by SergGr
回答by John Bode
Are you simply appending string literals? Or are you going to be appending various data types (ints, floats, etc.)?
你只是简单地附加字符串文字吗?还是要附加各种数据类型(整数、浮点数等)?
It might be easier to abstract this out into its own function (the following assumes C99):
将其抽象为自己的函数可能更容易(以下假设为 C99):
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
int appendToStr(char *target, size_t targetSize, const char * restrict format, ...)
{
va_list args;
char temp[targetSize];
int result;
va_start(args, format);
result = vsnprintf(temp, targetSize, format, args);
if (result != EOF)
{
if (strlen(temp) + strlen(target) > targetSize)
{
fprintf(stderr, "appendToStr: target buffer not large enough to hold additional string");
return 0;
}
strcat(target, temp);
}
va_end(args);
return result;
}
And you would use it like so:
你会像这样使用它:
char target[100] = {0};
...
appendToStr(target, sizeof target, "%s %d %f\n", "This is a test", 42, 3.14159);
appendToStr(target, sizeof target, "blah blah blah");
etc.
等等。
The function returns the value from vsprintf, which in most implementations is the number of bytes written to the destination. There are a few holes in this implementation, but it should give you some ideas.
该函数返回值 from vsprintf,在大多数实现中是写入目标的字节数。这个实现有一些漏洞,但它应该给你一些想法。
回答by wkz
I think you are looking for fmemopen(3):
我认为您正在寻找fmemopen(3):
#include <assert.h>
#include <stdio.h>
int main(void)
{
char buf[128] = { 0 };
FILE *fp = fmemopen(buf, sizeof(buf), "w");
assert(fp);
fprintf(fp, "Hello World!\n");
fprintf(fp, "%s also work, of course.\n", "Format specifiers");
fclose(fp);
puts(buf);
return 0;
}
If dynamic storage is more suitable for you use-case you could follow Liam's excellent suggestion about using open_memstream(3):
如果动态存储更适合您的用例,您可以遵循 Liam 关于使用的极好建议open_memstream(3):
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *buf;
size_t size;
FILE *fp = open_memstream(&buf, &size);
assert(fp);
fprintf(fp, "Hello World!\n");
fprintf(fp, "%s also work, of course.\n", "Format specifiers");
fclose(fp);
puts(buf);
free(buf);
return 0;
}
回答by McBartok
I find the following method works nicely.
我发现以下方法效果很好。
sprintf(Buffer,"Hello World");
sprintf(&Buffer[strlen[Buffer]],"Good Morning");
sprintf(&Buffer[strlen[Buffer]],"Good Afternoon");
回答by ravibhuva9955
You can use the simple line shown below to append strings in one buffer:
您可以使用下面显示的简单行在一个缓冲区中附加字符串:
sprintf(Buffer,"%s %s %s","Hello World","Good Morning","Good Afternoon");

