C - reading a line from a buffer of a certain size

I have char buf [x] , int s and void * data i>.

I want to write a string of size s to data from buf .

How to do it?

Thanks in advance.

+3
source share
5 answers

Assuming that

  • "string" means a zero-terminated string, as is usually implied in C;
  • You have not allocated a memory in data;
  • You already know that s <= x

First you need to allocate memory in data. Do not forget the byte room 0at the end of the line.

data = malloc(s+1);
if (data == NULL) {
    ... /*out-of-memory handler*/
}

, malloc , .

, , strncat. ( , C89.) , :

*(char*)data = 0;
strncat(data, buf, s);

, , :

  • strlcpy ( C, Unix-, public domain):

    strlcpy(data, buf, s+1);
    
  • , s , memcpy:

    memcpy(data, buf, s);
    

    ((char *)) [s + 1] = 0;

  • :

    size_t bytes_to_copy = strlen(buf);
    if (bytes_to_copy > s) bytes_to_copy = s;
    memcpy(data, buf, bytes_to_copy);
    ((char*)data)[s+1] = 0;
    
  • strncpy, , s:

    strncpy(data, buf, s);
    ((char*)data)[s+1] = 0;
    
+4

data :

char buf[] = "mybuffer";
void *data = malloc(strlen(buf)+1);
strcpy((char*)data,buf);

, ,

char buf[] = "mybuffer";
void *data= (void*)strdup(buf);
+3
memcpy(data, buf, s);

This assumes you have enough space in the data (and in buf).

Depending on what you are doing (you are not saying, but you are saying that you are copying the lines), you may want to add zero at the end of your new copied line if you did not copy the null value to buff and you are going to use the data in the function that expects a string.

+2
source
data = malloc(s);
strcpy((char*)data,buf);
free(data);
+2
source
int n = MIN((x - 1), s);
char *bp = buf;
char *dp = (char *)data;
while (n--) {
  *bp++ = *dp++;
}
*dp = '\0';
+2
source

Source: https://habr.com/ru/post/1755191/


All Articles