Skip to content
Advertisement

Should I bother about user might mess up my program’s files?

I am writing a C++ program for Linux which creates some files on the disk during the work. These files contain information about program’s internal objects state, so that the next time the program is started it reads these files to resume previous session. Some of these files are also being read/written to during the execution to read/write some variables values. The problem is that modifying/renaming/deleting these files would lead in undefined behavior, segmentation faults and other surprises causing the program to crash. I am certainly not going to restrict the user in accessing files on his/her machine, but inside the program I can always check if a file has been modified before accessing it to at least prevent the program from crash. It would involve many extra checks and make the code larger though.

The question is what is a good practice to deal with such issues? Should I even be so paranoid, or just expect the user to be smart enough to not mess with program’s files?

Advertisement

Answer

First, check your resources and if it is worth the effort. Will the user be even tempted to trace and edit these files?

If so, my advice is this: Don’t be concerned whether or not the file has been modified. Rather you should validate the input you get (from the file).

This may not be the most satisfying answer, but error handling is a big part of programming, especially when it comes to input validation.

Let assume you are writing into a ~/.config/yourApp/state.conf.

  • Prepare defaults.
  • Does the file exist? If not use defaults.
  • Use some well known structure like INI, JSON, YAML, TOML, you name it, that the user can understand and the application can check for integrity (libraries may help here). If the file is broken use defaults.
  • In case the user does delete a single entry, use the default value.
  • Some values deserve special checking in case a out of bound access would lead to undefined behavior. If the values is out of bounds, use a default.
  • Ignore unknown fields.
  • In case you can’t recover from a malformed input, provide a meaningful error message, so the user may be able to restore a save state (restore from a backup or start over from the beginning).
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement