c - 逐行写?

标签 c fwrite

我有下面的代码。我想逐行写入所有新数据,我该怎么做?我的代码工作正常,但它写入的数据彼此相邻。

////////////////////////////////////
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);

最佳答案

您创建的字符串没有换行符:

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

试试这个:

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

关于c - 逐行写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10390290/

相关文章:

c - 处理 C "if "条件下溢 - 使用 boolean 值

c - 未初始化的指针的计算结果是 true、false 还是导致未定义的行为?

c 如何 union 让你将数据视为一个字节数组

c - 为什么会出现段错误(核心转储)?

c - C 中 fwrite 和 struct 的奇怪错误

c - 如何确定char指针数组元素的总字符长度?

c - 为什么不能触发子进程中的信号处理程序?

c - 将两个以上的 "struct"写入文件的问题,然后读取文件

C 以二进制模式读/写文件

c++ - 将用户定义的数据类型保存到 C++ 文件中