John Bode <> writes:
> On May 10, 3:36Â*pm, john <j...@nospam.com> wrote:
>> I am trying to write a portable C program.
>>
>> However I have this problem. I need to get the user to input a filename
>> to save the results. But if he shall input a filename not in the form 8.3
>> then this will not be portable to DOS.
>>
>
> Sure it will. If the user insists on entering a string that isn't a
> valid DOS file name, then that's the *user's* problem, not your code's
> (modulo properly escaping backslashes in the path name and other
> sanity checks; i.e. if the user enters "\a\path\name.txt", you need to
> change it into "\\a\\path\\name.txt"). All your code has to do is
> pass the string to fopen() and check the result. If the user entered
> a bad filename, fopen() should return NULL, and you can then prompt
> the user to try again (or cancel the operation).
No, you don't need to escape backslashes in user-entered strings.
Backslashes need to be doubled only in string literals and character
constants.
If you read a string with fgets() (and drop the terminating
'\n'), you can pass that string directly to fopen(). If you try
to double the backslashes first, fopen() will see a string with
doubled backslashes.
As for portability, there are contexts in which you might want to
limit file names to the least common denominator, which might be
the DOS-style 8.3 format. For example, if you're distributing data
files, avoiding longer names can make your files more portable to a
wider variety of systems. More realistically, making sure you don't
have distinct file names that differ in case can be beneficial for
files that might be ported from, say, Unix to Windows.
But restricting the behavior of fopen() itself is not the way
to do this. It would have the very small benefit of warning you
about file names that might not be portable, but the huge drawback
of making it impossible to deal with any such files even when you
don't care whether DOS can support them.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"