Reputation: 195
I'm writing a fairly basic program for personal use but I really want to make sure I use good practices, especially if I decide to make it more robust later on or something.
For all intents and purposes, the program accepts some input files as arguments, opens them using fopen()
read from the files, does stuff with that information, and then saves the output as a few different files in a subfolder. eg, if the program is in ~/program
then the output files are saved in ~/program/csv/
I just output directly to the files, for example output = fopen("./csv/output.csv", "w");
, print to it with fprintf(output,"%f,%f", data1, data2);
in a loop, and then close with fclose(output);
and I just feel like that is bad practice.
Should I be saving it in a temp directory wile it's being written to and then moving it when it's finished? Should I be using more advanced file i/o libraries? Am I just completely overthinking this?
Upvotes: 6
Views: 3772
Reputation: 72657
Best practices in my eyes:
printf ("hello, world\n");
and not "\nHello, world"
like those mislead by the Mighty William H. often write to cope with the sillyness of their command shell. Outputting newlines first breaks line buffered I/O.Upvotes: 9
Reputation: 6610
If no other program is checking for the presence of ~/program/csv/output.csv
for further processing, then what you're doing is just fine.
Otherwise you can consider writing to a FILE *
obtained by a call to tmpfile
in stdio.h or some similar library call, and when finished copy the file to the final destination. You could also put down a lock file output.csv.lck
and remove that when you're done, but that depends on you being able to modify the other program's behaviour.
Upvotes: 0
Reputation: 8195
It's fine. I/O is fully buffered by default with stdio
file functions, so you won't be writing to the file with every single call of fprintf
. In fact, in many cases, nothing will be written to it until you call fclose
.
It's good practice to check the return of fopen
, to close your files when finished, etc. Let the OS and the compiler do their job in making the rest efficient, for simple programs like this.
Upvotes: 1
Reputation:
Am I just completely overthinking this?
You are. If the task's simple, don't make a complicated solution on purpose just because it feels "more professional". While you're a beginner, focus on code readability, it will facilitate your and others' lives.
Upvotes: 4