Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some best practices for file I/O in C?

Tags:

c

file

io

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?

like image 888
Chris Gorman Avatar asked Mar 14 '13 20:03

Chris Gorman


1 Answers

Best practices in my eyes:

  • Check every call to fopen, printf, puts, fprintf, fclose etc. for errors
  • use getchar if you must, fread if you can
  • use putchar if you must, fwrite if you can
  • avoid arbitrary limits on input line length (might require malloc/realloc)
  • know when you need to open output files in binary mode
  • use Standard C, forget conio.h :-)
  • newlines belong at the end of a line, not at the beginning of some text, i.e. it is 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.
  • if you need more than 7bit ASCII, chose Unicode (the most common encoding is UTF-8 which is ASCII compatible). It's the last encoding you'll ever need to learn. Stay away from codepages and ISO-8859-*.
like image 141
Jens Avatar answered Nov 10 '22 15:11

Jens