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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Assuming that
data;First you need to allocate memory in
data. Don’t forget the room for the0byte at the end of the string.Assuming
mallocsucceeds, 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
scharacters 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: