1

以下のコードがあります。すべての新しいデータを 1 行ずつ書き込みたいのですが、どうすればよいですか? 私のコードは正常に動作しますが、データを隣同士に書き込みます。

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

3 に答える 3

3

改行なしで文字列を作成します。

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

これを試して:

sprintf(log_sensor_event, "%s\n %s",timedate, USERID);
于 2012-04-30T20:45:27.957 に答える
2

'\n'文字列の間に改行 ( ) 文字を挿入する必要があります。

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

末尾の '\n' に注意してください。

于 2012-04-30T20:46:09.590 に答える
1

交換してみませんか

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

...
write(log_sensor_event, sizeof(log_sensor_event[0]), sizeof(log_sensor_event)/sizeof>(log_sensor_event[0]), fp2);
fputc('\n', fp2);

単に

fprintf(fp2, "%s %s\n", timedate, USERID);

これにより、多くの呼び出しとローカル バッファーが回避されます。

I/O のバッファリングは で設定できますsetvbuf

于 2012-05-01T09:04:40.200 に答える