This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
- C
- C
- Clojure
- C++
- C#
- D
- D
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Haskell
- JS
- Java
- Java
- Kotlin
- Lisp
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Python
- Ruby
- Rust
- Rust
- Scala
- Smalltalk
- VB
FILE *file;
size_t len=0;
char *lines;
assert(file=fopen(f,"rb"));
assert(lines=malloc(sizeof(char)));
while(!feof(file))
{
assert(lines=realloc(lines,(len+0x1000)*sizeof(char)));
len+=fread(lines,1,0x1000,file);
}
assert(lines=realloc(lines,len*sizeof(char)));
int err = 0;
int fd = 0;
void * ptr = NULL;
struct stat st;
if ((fd = open (f, O_RDONLY))
&& (err = fstat (fd, &st)) == 0
&& (ptr = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) != -1) {
const char * lines = ptr;
puts (lines);
munmap (ptr, st.st_size);
close (fd);
}
Mapping the whole file into the process address space avoids allocating memory.
std::string fromFile(std::string _f)
{
std::ifstream t(_f);
t.seekg(0, std::ios::end);
size_t size = t.tellg();
std::string buffer(size, ' ');
t.seekg(0);
t.read(&buffer[0], size);
}
var lines = new File(f).readAsStringSync();
Defaults to UTF-8 encoding.
To get lines directly, use:
file.readAsLinesSync()
To get lines directly, use:
file.readAsLinesSync()
byte[] encoded = Files.readAllBytes(Paths.get(f));
String lines = new String(encoded, StandardCharsets.UTF_8);
You have to know and explicitly tell the charset used in the file.
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
import java.io.File;
import java.util.Scanner;
File F = new File(f);
try (Scanner s = new Scanner(F)) {
s.useDelimiter("\\R");
String n = lineSeparator(),
lines = s.tokens()
.collect(joining(n));
}
NSString *lines=[NSString stringWithContentsOfFile:f encoding:e error:NULL];
The file encoding is pretty important here, is it not? For encodings available see the docs link.
$lines = file_get_contents('f');
if ($lines === false) {
// handle error...
}
lines has the string type if file_get_contents was successful.
You can split this string with explode, or directly use file to read a file into an array of lines.
You can split this string with explode, or directly use file to read a file into an array of lines.
open my $fh, '<', $f;
my $lines = do { local $/; <$fh> };
close $fh;
local $/ tells perl to temporarily (within the braces) clear the "end of line" terminator, causing it to read the entire file as a single string.