I'm curious to see how different languages handle trivial functionality.
Write the shortest function possible that opens a file for reading, copies the contents to a string, and returns a string or pointer to a string.
I'll start with C.char *create_buffer_from_file(const char *filename)
{
FILE *fp = fopen(filename, "rb");
fseek(fp, 0, SEEK_END);
long len = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buf = (char *) malloc(sizeof(char) * len + 1);
fread(buf, len, 1, fp);
buf[len] = 0;
fclose(fp);
return buf;
}
>>55334423
def kek(name):
with f as open(name):
return f.read()
No exception handlingpublic static void readFile(string path) {
return File.Exists(path) ? File.ReadAllLines(path) : "";
}
>>55334423var fs = require(fs);
var readFile = function (path) {
return fs.readFileSync(path);
};
(define (foo file) (get-string-all (open-input-file file)))
[\code]
import open_a_file_for_reading_copy_the_contents_to_a_string_and_return_a_string_or_pointer_to_a_string
>>55334699
>void
>return
Woops
>>55337269
Well you can use the return statement in procedures/corountines too
Just don't return anything
>>55334699
What are you doing nigger?public static string ReadFile(string path) => File.Exists(path) ? File.ReadAllText(path) : "";
>>55337325
Fucking pajeet.
You're supposed to return null here, how would the user make the difference between an empty file and a non existing one?
open System
open System.IO
open System.Text
let main args =
let path = "file.txt"
let text =
if File.Exists path then
Some File.ReadAllText path
else
None
0
Something like that, didn't bother to test.
In poothon:
stuff = open('blah.txt').read()
>>55337357
I pity the person who has to look at your disgusting code.
That is obviously a helper method, if you actually cared if the file existed or not you'd use the File methods yourself.
This way you can easily use the return value in a for loop or a method that can handle empty strings, without doing an ugly if check..
>>55337749
It's a helper method, and it doesn't even follow the most basic practices. It is in fact so short I don't even get why you make it a helper method, you may as well just make the call yourself.