Reputation: 3
The system call read()
takes characters from a file and it also reads characters that don't exist at the end of each buffer.
The file has string: "AAOOOOOBRRRRRRIIIIIGGGGGGIIIIIINNNNNAAAALLLLLEEEEXXZZZSS"
When it reads, the buffer contains: "AAOOOOOBRRRRRRIIIIIGGGGGGIIIIIINNNNNAAAALLLLLEEEEXXZZZSS??Bf?"
As you see, the last four characters don't exist in the file
My code:
void trOpcionS(int src, int dst, char *cadena)
{
//BUFFER DE LECTURA
char buff[100];
//BUFFER DE ESCRITURA TRAS ANALIZAR EL DE LECTURA
char buffRes[100];
//bytes leidos
ssize_t r = 0;
//bucle de lectura
while ((r = read(src, buff, 100)) > 0)
{
char *ptrBuf = buff;
char *ptrBufRes = buffRes;
//bucle para analizar la lectura
while (*ptrBuf != '\0')
{
//BUCLE QUE RECORRE EL BUFFER
int pos = 0;
while (*(cadena + pos) != '\0')
{
//BUCLE QUE RECORRE LA CADENA A TRANSFORMAR
if (*(cadena + pos) == *ptrBuf)
{
//SI ENCUENTRO UNA EQUIVALENCIA, SE ESCRIBE Y SE SALTAN TODAS SUS REPETICIONES
*ptrBufRes = *ptrBuf;
while (*(ptrBuf + 1) == *ptrBufRes)
{
ptrBuf++;
}
ptrBufRes++;
break;
}
pos++;
}
//SI EL VALOR NO SE ENCUENTRA EN LA CADENA SE ESCRIBE SIN MÁS
if (pos == strlen(cadena))
{
*ptrBufRes = *ptrBuf;
ptrBufRes++;
}
ptrBuf++;
}
*ptrBufRes = '\0';
printf("Reading: %s\n", buff);
printf("%s\n", buffRes);
ssize_t w = write(dst, buffRes, strlen(buffRes));
}
}
Upvotes: 0
Views: 122
Reputation: 16540
this statement sequence:
while ((r = read(src, buff, 100)) > 0)
{
needs to be followed by:
buf[ r ] = '\0';
so as to NUL terminate the read string because the function: read()
does not do that.
Upvotes: 0
Reputation: 32596
while((r = read(src, buff, 100)) > 0){
char* ptrBuf = buff;
char* ptrBufRes = buffRes;
//bucle para analizar la lectura
while(*ptrBuf != '\0'){ //BUCLE QUE RECORRE EL BUFFER
after you read the buffer you missed to add the final null character the second while expect, so that one continues up to find a null character you never set, of course this is an undefined behavior.
You can add the null character at buff[r] but that supposes you read up to 99 bytes rather than 100 or buff needs to be sized 101, else just replace the second while by
while (ptrBuf != (buff + 100)) {
Warning there is also a problem in the loop
while(*(ptrBuf + 1) == *ptrBufRes)
where you can go out of the read bytes / out of buff
Upvotes: 1