2

I am getting an error when I try to write a file in Ruby v2.3.3 to a folder on Windows.

This is code that I've used many times before and it's worked fine.

File.open(file_name, "w+") { |out| out.puts "Hello" }

This works for short file names, but apparently fails around 200 character files names (including the folder path). The error I get is that the file or folder does not exist. The method is creating the file, so it obviously does not need to exist beforehand. And the folder definitely does exist -- I tested that many times. So I do not understand the error message.

I tried running this with a somewhat shorter file name, and then it worked fine.

Is there a way around this error? Is this really a Ruby error, or more like a Windows limitation?

tadman
  • 208,517
  • 23
  • 234
  • 262
Glenn
  • 436
  • 1
  • 3
  • 12

1 Answers1

4

There's a hard limit on how long a path can be in Windows, at around 260 characters:

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters.

Every operating system has some kind of limit in order to allow C programs to allocate buffers of appropriate length. PATH_MAX varies from one operating system to another but is usually in the 255-1024 range.

This question goes into a lot more detail on the implications of this sort of thing as it pertains to Windows.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 2
    In Windows 10, the `MAX_PATH` limit is removed in most cases if long-path support is enabled both at the system level and in the application manifest (i.e. ruby.exe I suppose). In all versions of Windows NT, we can use long paths if we manually compose a fully-qualified Unicode path (i.e. WINAPI `GetFullPathNameW`) and prefix it with the device root directory "\\?\". If it's a UNC device, we need to replace the initial "\\" with "\\?\UNC\". If it's a normal device path, replace "\\.\" with "\\?\". – Eryk Sun Aug 02 '19 at 06:59