Search code examples
cfwrite

fwrite line by line?


I have the code below. I would like to write all new data line by line, how can I do it? My code works fine but it writes the data next to each other.

////////////////////////////////////
char timedate[13];
char USERID[] ="100050"; 
char *p;
p=fetch_time(); //the function returns a string (char[13])
strcpy(timedate, p);

char log_sensor_event[20];
sprintf(log_sensor_event, "%s %s",timedate, USERID);

FILE *fp2;
fp2=fopen("/home/eagle/Desktop/log_file.txt", "ab");
if(fp2 == NULL){
    perror("log_file.txt open failed");
    exit(EXIT_FAILURE);
}
write(log_sensor_event, sizeof(log_sensor_event[0]), sizeof(log_sensor_event)/sizeof>(log_sensor_event[0]), fp2);
fputc('\n', fp2);
fclose(fp2);

Solution

  • You need to insert a newline ('\n') character between the strings:

    sprintf(log_sensor_event, "%s %s\n",timedate, USERID);
    

    Note the ending '\n'.