I have to read a file line by line using C system calls but I don't know how to detect the end of the file and I'm getting Segmentation Fault all the time because there is none on the last line \n
and it keeps reading the last character infinitely.
This is my function read line: (fd is the file descriptor)
int leerLinea(int fd, char linea[]){
char c;
int leidos=0;
int i=0;
read(fd,&c,1);
while(c!='\n' && c!=NULL){
linea[i]=c;
i++;
leidos++;
read(fd,&c,1);
}
linea[i] = '\n'; //por si quieres tener el \n en lo leido
return leidos;
}
The problem was that I was adding 1 to
leídos
each time I entered the loop instead of adding it after checking if the system call had worked well and my main program had the condition that if Ileídos > 0
called againleerLinea()
so a infinite loop since read was always > 0, with its respective Segmentation Fault. Nor was it necessary to check that the character was not NULL.Try adding in the conditional if it reached the end of the file:
}