Writing multiline text files in Lua - file

I would like to know the best way to make my script write something into a file (lets say text.txt) in a way that would always add a line break at the end. When I append text using
file = io.open("test.txt", "a")
file:write("hello")
twice, the file looks like:
hellohello
But I want it to look like:
hello
hello

Unlike print, the new line character isn't added automatically when calling io.write, you can add it yourself:
file:write("hello", "\n")

The easiest way to achieve this would be to include a Newline character sequence every time you call the write method like so: file:write("hello\n") or so: file:write("hello", "\n"). This way, a script such as
file = io.open(test.txt, "a")
file:write("hello", "\n")
file:write("hello", "\n")
would result in the desired output:
hello
hello
There are, however, many other solutions to this (some being more elegant than the others). When outputting text in Java, for example, there are special methods such as BufferedWriter#newLine(), which will do the same thing in a more cleaner fashion. So if your interested in a different way of achieving this, I suggest you read up on the Lua docs for analogous methods/solutions.

Related

How to read lines from a file (.txt, .asm)

Like my input would be stored in a .txt/.asm file, and the input is kind of like this:
MOV Ri,Rj
MVI Ri,X
LOAD Ri,X(Rj)
STORE Ri,X(Rj)
So, I need to read them line by line and also store these. What is the best way to do this? Like I have checked fscanf. But it seems like it will handle cases best when there is data of fixed format, like (Hi, 2) (Bye, 3) (Hello, 4). But how should I go about handling my case? It should be able to read the entire line and then stop after the input finishes.
I apologize in advance if something like this has been asked earlier, but I couldn't find a question which matched what I asked.

Advice on reading multiple text files into an array with Ruby

I'm currently writing out a program in Ruby, which I'm fairly new at, and it requires multiple text files to be pushed into an array line by line.
I am currently unable to actually test my code since I'm at work and this is for personal use, but I'm seeking advice to see if my code is correct. I knows how to read a file and push it to the array. If possible can someone check it over and advise if I have the correct idea? I'm self taught regarding Ruby and have no-one to check my work.
I understand if this isn't the right place for trying to get this sort of advice and it's deleted/locked. Apologies if so.
contentsArray = []
Dir.glob('filepath').each do |filename|
next if File.directory?(filename)
r = File.open("#{path}#{filename}")
r.each_line { |line| contentsArray.push line}
end
I'm hoping this snippet will take the lines from multiple files in the same directory and stick them in the array so I can later splice what's in there.
Thank you for the question.
First let's assume that 'filepath' is something like the target pattern you want to glob in Dir.glob('filepath') (I used Dir.glob('src/*.h').each do |filename| in my test).
After that, File.open("#{path}#{filename}") prepends another path to the already complete path you'll have in filename.
And lastly, although this is probably not the problem, the code opens the file and never closes it. The IO object provides a readlines method that takes care of opening and closing the file for you.
Here's some working code that you can adapt:
contentsArray = []
Dir.glob('filepath').each do |filename|
next if File.directory?(filename)
lines = IO.readlines(filename)
contentsArray.concat(lines)
end
puts "#{contentsArray.length} LINES"
Here are references to the Ruby doc's for the IO::readlines and Array::concat methods used:
https://ruby-doc.org/core-2.5.5/IO.html#method-i-readlines
https://ruby-doc.org/core-2.5.5/Array.html#method-i-concat
As an alternative to using the goto (next) the code could conditionally execute on files, like this:
if File.file?(filename)
lines = IO.readlines(filename)
contentsArray.concat(lines)
end

how to get the file extension in pike

I'm working on a program in pike and looking for a method like the endswith() in python- a method that gives me the extension of a given file.
Can someone help me with that?
thank you
Python's endswith() is something like Pike's has_suffix(string s, string suffix):
has_suffix("index.html", ".html");
Reference:
http://pike.lysator.liu.se/generated/manual/modref/ex/predef_3A_3A/has_suffix.html
extract the end of the string, and compare it with the desired extension:
"hello.html"[<4..] == ".html"
(<4 counts from the end of the string/array)
If you want to see what the extension of a file is, just find the last dot and get the substring after it, e.g. (str/".")[-1]
If you just want to check if the file is of a certain extension, using has_suffix() is a good way, e.g. has_suffix(str, ".html")

How to write an elisp function returning the contents of a file as a string?

Well, the title has it all;). Of course, I can create a new buffer, insert-file-contents into it, then put it into a variable, kill the buffer and return the variable - but this seems an overkill. Is there a better way?
NB. My use case is an .emacs declaration of smtpmail-auth-credentials - I have my password in some file, and don't want to put it in .emacs again.
I believe there's no easy way to do what you want without involving buffers. I'd use a temporary buffer like so:
(defun file-contents (filename)
(interactive "fFind file: ")
(with-temp-buffer
(insert-file-contents filename)
(buffer-substring-no-properties (point-min) (point-max))))
Though you may want to use insert-file-contents-literally if you don't want format decoding, auto uncompression, etc.

Find string in file, replace everything after "="?

I would like to read a file, find some strings and replace everything that is after the symbol "=" in this line.
Lets say I have a textfile like this:
name=whatever
age=150
id.from.system=10298092_42_42
path=D:\name\somewhere
whatever_A= WHATEVER
Lets say I want to change path. At first I have to find the string "path" and then replace everything after "=" somehow. Any ideas? I know I could easily read the file line by line something like this:
val source = io.Source.fromFile("C:/myfile.txt)
val lines = source.mkString
source.close()
But this is maybe not the best idea, because its not that performant to read the whole file (maybe the file got 10000000 lines, and the string is already at line 2, but my program would read the whole file. That would be unnecessary).
And there is maybe another problem: if Im searching for specific strings, like here for "name" but these strings are there several times. I want to make sure that its only valid is after the string there is an "=". Maybe I could search always for something with an "=" at the end, that could solve the problem. But I have no idea how to write this in a nice scala code.
You can use an iterator to only iterate until you find the line you're looking for.
val source = io.Source.fromFile("somePath").getLines
val line = source.find(_.startsWith("path="))
line will contain the first line that starts with "path=".
If your C:/myfile.txt contains the line path=D:\name\somewhere, you can replace D:\name\somewhere with the following code:
val lines = fromString("path=D:\\name\\somewhere").getLines // use fromFile here
for { in <- lines
out <- if (in startsWith("path=")) "path=D:\\my\\path" else in
} yield out
This example will return the string
path=D:\my\path
You would need to use fromFile to get the lines and write the lines out to a new file.
Here's another approach that accomplishes the same thing:
val lines = fromString("path=D:\\name\\somewhere").getLines
lines.map(in => if (in startsWith("path=")) "path=D:\\my\\path" else in)

Resources