Aymanadou
Aymanadou

Reputation: 1220

C Programming - How to write a char into char*

Writing a character to the stream is ensured by several functions in C, such as :

 int fputc ( int character, FILE * stream );
 int putchar ( int character );
 int putc ( int character, FILE * stream );
...

My question is simple : is there any function which provide the possibility to write a character into a char*? (callback(int character, char * stream))

update :to explain more my problem i'am using lex/yacc compiling solution.
input() funcion returns the next character in the stream .I want to store for a specified condition the whole stream returned by this function into a variable.

Upvotes: 0

Views: 221

Answers (3)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43558

Since pointer arithmetic is in the very nature of C, there are no such functions. To put a character into some memory pointed to by stream and advance it, you would do:

*stream++ = character;

At the next sequence point stream will be pointing to the new, still unwritten character.

Of course, make sure that you don't advance stream beyond the bounds of its allocated area. To prevent this from happening you could do a simple calculation:

if (stream - base > BUFFER_SIZE) /* stop */

base would be a pointer to the beginning of the allocated area, the initial value of stream.

Upvotes: 2

harald
harald

Reputation: 6126

Sure, try snprintf if you need a function.

char buffer[BUFFER_SIZE];
char c = 'x';
snprintf(buffer, sizeof buffer, "%c", c);

If you're willinig to convert your char to a string first, you can also use strcat, strcpy etc.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258678

Why not directly access the pointer:

*stream = character;

Upvotes: 2

Related Questions