Search code examples
crystal-lang

How Do I Read a File in Crystal Lang?


I am familiar with Ruby and am trying to write a program in Crystal.

I have a file called special_file.txt that I want to read in my Crystal program, how do I do that?


Solution

  • Crystal is inspired by Ruby syntax and so you can often read and perform File operations in a similar manner. For example, Crystal has a File classclass which is an instance of the IO class containing a read method.

    To read a file's contents on your filesystem you can instantiate a File object and invoke the gets_to_end method coming from the IO super class:

    file = File.new("path/to/file")
    content = file.gets_to_end
    file.close
    

    The gets_to_end method reads an entire IO objects data to a String variable.

    You can also use a block invocation to achieve a similar result:

    # Implicit close with `open`
    content = File.open("path/to/file") do |file|
      file.gets_to_end
    end
    

    Finally, the most idiomatic way to read the contents of an entire file would be the one line:

    # Shortcut:
    content = File.read("path/to/file")