I've written a user space program to read from a kernel device line by line, somehow, the data is always overriden with each read. Can you please tell me how to fix my code?
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#define BUFFER_LENGTH 256
int main()
{
int ret,fd;
char buffer[BUFFER_LENGTH];
FILE * fPtr;
unsigned int i=0;
if((fd = open("/dev/show_log_device_dev", O_RDWR)) == -1){
perror("Failed to open the file");
}
//printf("/dev/show_log_device_dev opened.\n");
//fflush(stdout);
fPtr = fopen("log.txt", "w+");
int bytesRead = 0;
while (bytesRead < sizeof(buffer)) {
int ret = read(fd, buffer + bytesRead, sizeof(buffer) - bytesRead);
if (ret == 0)
break;
if (ret == -1) {
perror("Failed to read the message from the device.");
return errno;
/* Handle error */
}
bytesRead += ret;
printf("read from /dev/show_log_device_dev. %s\n",buffer);
}
if(lseek(fPtr,0,SEEK_SET)!=0) {
fprintf(fPtr,"%s",buffer);
}
fclose(fPtr);
}
I would like the output file "log.txt" to contain all the lines written to buffer with each read line after line sith skip-line between lines. Please show me the proper way to do it inctead of the fprintf attempt I've written above.
Thank you.