0
votes

I wanted to ask what will be the equivalent of this write statement in printf statement?

write(STDOUT_FILENO, buf + start, end - start);

Where buf is a char*, start is int, end is int. The line which is confusing me is buf + start? Or how can i save this to a char array using strcpy and then printf that char array. But i don't know how to copy the output of above code to char array. I am unable to understand what the line buf+start is doing.

thanks

2
what are you trying to do?Iharob Al Asimi
I want to save the output of above line to a char array so that i can use it.user2603796
It's simple pointer arithmetic. Are you looking for memcpy?5gon12eder

2 Answers

2
votes

The expression buf + start uses pointer arithmetic and is equivalent to &buf[start], the pointer to the position start in buf. The code you show prints the slice from start to end (exclusivley) of your char buffer buf.

If your buffer doesn't contain zeros, you can rewrite that as:

printf("%.*s", (int) (end - start), buf + start);

The cast to (int) isn't strictly necessary in your case, but the * precision in printf requires an int and one often uses size_t for positions, so I've made that a habit.

1
votes

To copy this data you need

char *mybuffer;
mybuffer = malloc(end - start + 1);
if (mybuffer != NULL)
{
    memcpy(mybuffer, buf + start, end - start);
    mybuffer[end - start] = '\0';
}

There you go, now mybuffer can be used in a printf like function, you need to remember to do free(mybuffer) at some point after you are done using mybuffer. Also you need to check end - start >= 0 and be aware that if there is a null byte embeded into the data, the string will be shorter than end - start for what printf and family care.