Created
March 23, 2023 00:01
-
-
Save lostsh/673cc92bb85cc0b370092c237b4de82c to your computer and use it in GitHub Desktop.
C99 input from pipe ouput stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
/** | |
* Read input char by char and ouput it. | |
*/ | |
int main(int argc, char* argv[]){ | |
int read_status = 1; | |
while(read_status){ | |
char c; | |
read_status = read(STDIN_FILENO, &c, 1); | |
// eventually do things | |
write(STDOUT_FILENO, &c, 1); | |
} | |
return 0; | |
} |
Author
lostsh
commented
Mar 23, 2023
pipe.c
Using stdio hight level primitives
#include <stdio.h>
/**
* Read input char by char and ouput it.
*/
int main(int argc, char* argv[]){
char c;
do{
c = getc(stdin);
//do things ?
printf("%c", c);
}while(c != '\0' && c != '\n');
return 0;
}
pipe.c
Storing input on allocated memory
#include <stdio.h> //printf getc
#include <stdlib.h> //alloc
/**
* Read input char by char and ouput it.
*/
int main(int argc, char* argv[]){
char *input = malloc(sizeof(char));
*input = '\0';
short unsigned int input_size = 1;
char c;
do{
c = getc(stdin);
input = realloc(input, (input_size+1)*sizeof(char));
*(input+(input_size-1)) = c;
*(input+(input_size)) = '\0';
input_size++;
}while(c != '\0' && c != '\n');
input_size-=2;
input = realloc(input, (input_size)*sizeof(char));
*(input+(input_size)) = '\0';
printf("string is : [%s] size : %d\n", input, input_size);
free(input);
input = NULL;
return EXIT_SUCCESS;
}
pipe.c
With memory allocation in a proper function
#include <stdio.h> // printf getchar
#include <stdlib.h> //alloc
/* Read input from stdin return the input size
* allocate the input string buffer. */
int getPipeInput(char **input){
*input = malloc(sizeof(char));
(*input)[0] = '\0';
short unsigned int input_size = 1;
char c;
do{
c = getchar();
*input = realloc((*input), (input_size+1)*sizeof(char));
(*input)[input_size-1] = c;
(*input)[input_size] = '\0';
input_size++;
}while(c != '\0' && c != '\n');
input_size-=2;
*input = realloc(*input, (input_size+1)*sizeof(char));
(*input)[input_size] = '\0';
return input_size;
}
int main(int argc, char **argv){
char *in;
int size = getPipeInput(&in);
printf("[%s] => %d\n", in, size);
free(in);
in = NULL;
// Exit success
return (EXIT_SUCCESS);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment