C-从一定大小的缓冲区中读取字符串
我有一个 char buf[x]
、int s
和 void* data
。
我想将一个大小为 s
的字符串从 buf
写入到 data
中。
我怎样才能实现它?
提前致谢。
I have a char buf[x]
, int s
and void* data
.
I want to write a string of size s
into data
from buf
.
How can I accomplish it?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设
data
中分配内存;首先您需要在
data
中分配内存。不要忘记字符串末尾0
字节的空间。假设
malloc
成功,您现在可以复制字节。编辑:
正如caf所指出的,这项工作的最佳功能是
strncat
。(它是完全可移植的,是C89的一部分。)它附加到目标字符串,因此预先将目标安排为空字符串:其他较差的可能性,保留在这里作为相关函数的示例:
如果您有
strlcpy
(这是不是标准 C,但在现代 Unix 系统上很常见;有公共领域的实现):如果你知道有源字符串中至少有
s
个字符,您可以使用memcpy
:((char*)data)[s+1] = 0;
否则,您可以先计算源字符串的长度:
或者您可以使用
strncpy
,但如果源字符串的实际长度小得多,则效率较低比s
:Assuming that
data
;First you need to allocate memory in
data
. Don't forget the room for the0
byte at the end of the string.Assuming
malloc
succeeds, you can now copy the bytes.EDIT:
The best function for the job, as pointed out by caf, is
strncat
. (It's fully portable, being part of C89.) It appends to the destination string, so arrange for the destination to be an empty string beforehand:Other inferior possibilities, kept here to serve as examples of related functions:
If you have
strlcpy
(which is not standard C but is common on modern Unix systems; there are public domain implementations floating around):If you know that there are at least
s
characters in the source string, you can usememcpy
:((char*)data)[s+1] = 0;
Otherwise you can compute the length of the source string first:
Or you can use
strncpy
, though it's inefficient if the actual length of the source string is much smaller thans
:如果没有分配
data
:实际上如果确实要定义数据,你也可以这样做
If
data
is not allocated:Actually if data is really to be defined you can also do
这假设您有足够的数据空间(和 buf)。
根据你正在做的事情(你没有说,但你确实说你正在复制字符串),如果你没有复制 buff 中已经存在的空值,你可能需要在新复制的字符串末尾添加一个空值,您将在需要字符串的函数中使用数据。
This assumes that you have enough space in data (and in buf).
Depending on what you are doing (you don't say, but you do say that you are copying strings), you may want to add a null at the end of your newly copied string if you did not copy a null already in buff, and you are going to use data in a function that expects strings.