Reading and writing files in C
Archive - Originally posted on "The Horse's Mouth" - 2010-01-12 23:39:00 - Graham EllisIn C you can use either open or fopen to open a file. open is what you would use for binary files, and you have plenty of low level controls; use fopen for text files.
When you fopen a file, you'll get back a pointer to a structure of type FILE which you then pass into function such as fgets and fprintf.
Each call to fgets reads the next line from the incoming file (up to a certain number of characters) and puts it into a character array. There's no need to move any pointers on to say where in the file you're going to read from - that's automatic as fgets is what we call an "iterator".
fgets returns the number of characters it has read; if you have an empty line in the incoming file you still get "1" back as there's a new line character (which is also included in the string you get). "0" indicates that there is no more data - i.e. you have reached the end of the file - and so that's how you test to know when to stop.
Remember that (in C) a character string has a null on the end of it, so if you're telling your program to read up to (say) 128 characters in a line, you have to dimension you char array to at least 129 ... otherwise you get undefined (and potentially nasty) results if the file you're reading has any lines longer than your maximum.
Finally, you should close your file(s) with fclose. For a file you're reading / files in programs that run quickly, you won't notice any difference if you forget. If you're writing to files in long-running programs, you may have more of an issue, as information that you think you have output may not reach the file until the program ends.
Example showing all of this ... [HERE] from the Learning to program in C course just concluded!