tags:

views:

43

answers:

2

Suppose a user selects a file in a dialogue box, and the app then opens the file for reading, etc. Users can open "incorrect" files--they can select a binary file, for example, even if the file they're supposed to be selecting is a text file.

I recognize that sometimes improper file types generate exceptions, which can be handled. But sometimes the files don't create exceptions; instead, they just cause the application to work improperly.

What's the standard way to code for these kinds of situations?

+1  A: 

A lot of operating systems help you out with this by providing filesystem APIs that are at least somewhat file-type-aware (in Cocoa for Mac OS X, there's a setAllowedFileTypes: method on NSOpenPanel, for example). Aside from that, you should make sure to define your file format in a way that's easy for you to identify when your program opens a file. A few well-known bytes at the start of your file is probably enough to protect you from most random-file problems.

Carl Norum
Thanks, Carl. As you and egon suggested, perhaps I'll just add a unique bit at the start of the file.
Al C
+1  A: 
  1. Put a unique identifier into the file (usually the first line or some tag)
  2. Restrict the file extension
  3. Do a check on the file whether it's OK

Use 1. if possible or use both 2. and 3.

egon
Thanks, egon. I'll prob. do #1, but I was a little unclear what you meant by #3.
Al C
#3 is just: validate the file beforehand. For example: if it's a xml file, you just check whether all tags are properly matched, CDATA tags properly used and everything you need for that program is there.Usually if you want to have a secure format. You use all three and then but some kind of checksum at the end of the file to validate the integrity. The checksum prevents users from easily editing the files.
egon