开发者

How are files validated when opened?

开发者 https://www.devze.com 2022-12-10 10:56 出处:网络
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

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 e开发者_JAVA百科xceptions, 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. 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消