Al C
Al C

Reputation: 5377

How are files validated when opened?

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?

Upvotes: 1

Views: 96

Answers (2)

Egon
Egon

Reputation: 1705

  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.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225172

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.

Upvotes: 1

Related Questions