the problem is if you increase buff size and also change the buff size in a3_fgets_2 function call to more than 15, the program will run in an infinite loop, Can anybody tell me why?
Thanks
#include<unistd.h>
#include<string.h>
char * a3_fgets ( char * str, int num, int fd );
char * a3_fgets_2 ( char * str, int num, int fd );
int main(int argc, char **argv){
char buff[15];
/*
while(fgets(buff, 256, stdin))
printf("%s", buff);
puts("\n================================");
*/
/*
while(a3_fgets(buff, 5, 0) != NULL)
printf("%s", buff);
puts("\n================================");
*/
while(a3_fgets_2(buff, 15, 0) != NULL){
write(1, buff, strlen(buff));
}
puts("\n================================");
return 0;
}
char * a3_fgets ( char * str, int num, int fd ){
char buffer;
int i = 0;
while(i < num-1 && read(fd, &buffer, 1) != 0){
str[i++] = buffer;
if(buffer == '\n')
break;
}
if(i == 0)
return NULL;
str[i] = '\0';
return str;
}
char * a3_fgets_2 ( char * str, int num, int fd ){
int i = 0;
memset(str, '\0', num);
if(read(fd, str, num-1) == 0)
return NULL;
while(i < num-1){
if(str[i++] == '\n')
break;
}
lseek(fd, i-(num-1), SEEK_CUR);
str[i] = '\0';
return str;
}
This is the data file that I use to check the program(its code, but I use it as input to the first program. Using input redirection)
char buffer[1];
int readVal = 0;
int i = 0;
while(i < num-1){
readVal = read(fd, buffer, 1);
if(i == 0 && readVal == 0)
return NULL;
else if(readVal == 0)
break;
str[i++] = buffer[0];
if(buffer[0] == '\n' || readVal == 0)
break;
}
str = '\0';
return str;