Reputation: 805
What does it mean to "read to" or "write to" a file? I am a beginner at CS and am fairly confused what is the meaning of these terms. Does "reading" a text file just mean printing it?
Upvotes: 1
Views: 164
Reputation: 14685
Your program usually operates in the realm of RAM - all your variables, literals, all the data your program manipulates, resides in this memory. When you need to work with the contents of a file that's stored in permanent storage (i.e. HDD or SSD), it first needs to be made accessible via the RAM. The most common way to do this is to send requests to the HDD or SSD to return the contents of a particular file, store those in RAM, and have a variable that refers to this part of memory so that your program can further work with it. This is what is meant by reading a file.
julia> pr = readlines("/home/Sundar/.julia/environments/v1.7/Project.toml")
2-element Vector{String}:
"[deps]"
"IJulia = \"7073ff75-c697-5162-941a-fcdaad2a7d2a\""
The contents of my Project.toml
file were stored in my SSD, but when I call readlines
, that sends a request (via the OS and the filesystem) for the contents of this file to be read into memory. The variable pr
then refers to these contents in the memory, and allows our program to use the contents for whatever purpose we need.
If I'd used pr = read("/home/Sundar/.julia/environments/v1.7/Project.toml")
instead (with read
instead of readlines
), these contents would have been returned as just a series of bytes. But since I called readlines
, the contents were interpreted as being UTF-8 encoded, and returned as String
s. Reading a file often involves this kind of choice of interpretation too - ultimately, every file is a series of bytes, but often it's more convenient to work with variables that contain a particular interpretation of those bytes.
Writing to a file is the opposite process, of taking some data that's in memory, and sending it to your HDD or SSD (again, via the OS and the filesystem) to be stored long term.
Upvotes: 2