I am having issues with outputting a string correctly that is coming from a 4K read buffer. Here is the code I have currently:
read_4K.c (cannot be modified)
int read_4K(char *b)
{
return read(0, b, 4096);
}
reader.c
static char Buffer[4096];
static int Bend = 0;
static int Bptr = 0;
int read_string(char *s,int size){
if(Bptr >= Bend){
Bend = read_4K(Buffer);
if(!Bend){
return 0;
}
Bptr = 0;
}
strncpy(s, &Buffer[Bptr], size);
Bptr += size;
}
bcat.c
main(int argc, char **argv)
{
int i;
char *str;
int bsize;
if (argc != 2 || sscanf(argv[1], "%d", &bsize) == 0 || bsize <= 0) {
fprintf(stderr, "usage: bcat strsize\n");
}
str = (char *) malloc(sizeof(char)*bsize);
if (str == NULL) { perror("malloc str"); exit(1); }
while (1) {
i = read_string(str, bsize);
if (i == 0) exit(0);
fwrite(str, 1, i, stdout);
}
}
When I execute this I get the following output
> ./bcat2 10 < input1.txt
Up and down the puppñies' hair ñ
Fleas andñ ticks jumñp everywheñre
'Causeñ of originñal sin
input1.txt:
Up and down the puppies' hair
Fleas and ticks jump everywhere
'Cause of original sin
I can't figure out why I am getting these garbage characters after the first read from the buffer... Can anyone help?