Here are some tips for when you are working with files :
- There is different in the way line break is stored between Windows and Unix-based [Linux,FreeBSD,etc] as a result, you must be careful when reading text files or getting input from the shell/prompt, because it might crash or worse, give incorrect information on other platforms. When the data entered has a line-break and you want to read a line, do not use scanf(“….\n“), either use filestream/cin.getline and process the line using something like sscanf(), or use multiple calls to cin (but before doing that, read tip #3
) - When giving the path for a file, instead of using ‘\’ , use ‘/’, so Unix-based operating systems can work with the code properly.
- The number of accesses to the file [if it's stored on the disk] can have a critical effect on the performance of your files. Try to maintain a balance between the size of the blocks you are reading and the number of calls you are going to do in a file to get the best performance. But if the file for example has 10 integers in a single line, make sure to get the line using cin.getline (The line can be long, careful to allocate enough space for the line) and then process that string from the memory, this can bring huge speedups to your program, because the seek-time for a hard-drive is far slower than in the memory.
- Binary formats are far faster than the text formats, when you want to keep a close eye on the data [like the early stages of the project] it is a very good idea to use Text mode, but when it is time to finalize the project and when you want to do performance improvements, add support for the binary formats [it's off-topic, but you better keep the text format capability maintained, it will be pretty useful for debugging]
- Don’t reinvent the wheel every time you program. To store configurations and also structured text data files, it is an excellent idea to use formats like XML. From Delphi to C++ to Java, all of them have good support [using external libraries if the compiler is not shipped with XML support] for the XML and there are a good number of XML processing/editing software available too.
- Don’t let the constantly growing files like logs become huge. Because there is a high chance that they will be heavily fragmented when stored on the hard-drive. Try splitting them up, for example if the program is constantly running, use a different log file for each day and store them appropriately [like organizing by date and using meaningful names for the log file] so consulting them would be easy.
- Make sure to close the files after you are done with them. Also if you’re program is saving a log, make sure to flush the buffer everytime you write to the file to find out what happened before your last crash.
Well, I think that’s it for now…