The code below works and writes all logs to one fixed file:
snprintf(filename, 128, "/var/log/api_record.log");
fp = fopen(filename, "a+");
if(fp){
PLIST_FOR_EACH_SAFE(&temp, record, tmp, list){
PLIST_DEL(&temp, &record->list);
fprintf(fp, "%.*s
", record->buflen, record->buf);
free(record->buf);
free(record);
}
fflush(fp);
fclose(fp);
}
Now I'm trying to get, say, host_name, and write each record to a different file, named by the record's host_name.
if(fp){
PLIST_FOR_EACH_SAFE(&temp, record, tmp, list){
PLIST_DEL(&temp, &record->list);
host_name = record->meta;
fprintf(fp, "%.*s
", record->buflen, record->buf); // The question is what's the fp?
free(record->buf);
free(record);
}
fflush(fp);
fclose(fp);
}
But I'm not sure how to maintain the fp's here. I can open and close a file with the desired filename with each record, like below, but it's costly. (do one fopen() per iteration of the loop)
snprintf(filename, 128, "/var/log/%s.log", host_name);
fp = fopen(filename, "a+");
Or possibly, traverse through the records as a preprocessing step and open the host_name named files beforehand, then map the host_name's to the fps through some hashmap? But that also sounds quite ugly.
How can I efficiently do this?
question from:
https://stackoverflow.com/questions/65832314/write-to-multiple-files-based-on-name-in-c 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…