[a / b / c / d / e / f / g / gif / h / hr / k / m / o / p / r / s / t / u / v / vg / vm / vmg / vr / vrpg / vst / w / wg] [i / ic] [r9k / s4s / vip] [cm / hm / lgbt / y] [3 / aco / adv / an / bant / biz / cgl / ck / co / diy / fa / fit / gd / hc / his / int / jp / lit / mlp / mu / n / news / out / po / pol / pw / qst / sci / soc / sp / tg / toy / trv / tv / vp / vt / wsg / wsr / x / xs] [Settings] [Search] [Mobile] [Home]
Board
Settings Mobile Home
/g/ - Technology

Name
Options
Comment
Verification
4chan Pass users can bypass this verification. [Learn More] [Login]
File
  • Please read the Rules and FAQ before posting.
  • You may highlight syntax and preserve whitespace by using [code] tags.

08/21/20New boards added: /vrpg/, /vmg/, /vst/ and /vm/
05/04/17New trial board added: /bant/ - International/Random
10/04/16New board for 4chan Pass users: /vip/ - Very Important Posts
[Hide] [Show All]


[Advertise on 4chan]


C++ :
    std::filesystem::path filePath(argv[1]);
std::ifstream file(filePath, std::ios::binary);
std::string fileSource((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
std::cout << fileSource << std::endl;

retarded


C :
    FILE* f = fopen(argv[1], "r");
fseek(f, 0, SEEK_END);
size_t sz = ftell(f);
fseek(f, 0, SEEK_SET);
char* src = malloc(sz+1);
fread(src, 1,sz, f);
fclose(f);
src[sz] = '\0';

printf("%s\n", src);

retarded


Python:
with open("file.txt") as file:
data = file.read()
print(data)

simple, just works


cniles and npc++ btfo
>>
File: IMG_0070.jpg (105 KB, 1080x1019)
105 KB
105 KB JPG
In Rust this is just
use std::fs;

fn main() {
let data = fs::read_to_string("file.txt").expect("Unable to read file");
println!("{}", data);
}

Note how it forces you to check for read errors too. Beautiful.
>>
>>106988012
hmm pretty good desu
>>
>>106987909
PHP
$data = file_get_contents("file.txt");
echo $data, "\n";
>>
File: one-piece-eneru.gif (2.92 MB, 518x640)
2.92 MB
2.92 MB GIF
Console.WriteLine(File.ReadAllText("file.txt"));
>>
>>106988144
pretty good too desu
>>
>>106987909
wait until you see what they all look like under the hood
>>
>>106987909
in C you know which system calls are happening
in python god knows what monstrosity is happening under the hood
>>
You just want the File content right ?
    int fd = open("test.txt", O_RDONLY);
char buf[1];
while (read(fd, buf, 1))
write(1, buf, 1);
close(fd);

Also >>106988236
>>
File: 1731556866731747.png (336 KB, 2139x191)
336 KB
336 KB PNG
>>106987909
left to right this is cpp,c and python of readong 1gb or random ascii from a text file and printing it to terminal (using the 'time' program, in fish shell in alacritty and compiling with no flags)

it appears that python is actually faster than c and cpp for some reason
>>
File: parliament-kot.png (309 KB, 800x800)
309 KB
309 KB PNG
>>106988435
post c code, and what flags you compiled it with
paiton is c under the hood so you should be able to get the same prformance even if the former is optimized to death
>>
>>106988435
Uh, cnile bros, our cope response?
>>106988465
nvm, it's already posted
>>
>>106988435
I suspect the difference in time would be printing to the shell
opening the file and reading it are system calls which are both limited by the kernel
but like this anon said >>106988465 post the code
>>
>>106987909
my @lines = <$input_fh>;
>>
File: kottest-reaction-2.gif (1.24 MB, 498x415)
1.24 MB
1.24 MB GIF
>>106988355
>>106988477
this?
this is the least efficient way of doing things
try reading and printing 100k chars at a time
make sure to enable -O3 and -march=native or their equivalents for your compiler. -funroll-all-loops to, well, unroll all loops. its free performance in this case. try with -flto, cross compilation unit optizations enabled, maybe theres some inlines that can happen
>>
>>106987909
the fuck is this C version lmao, are you retarded or did you write this garbage to ragebait people?
>>
File: lokinpoikanen.jpg (29 KB, 325x272)
29 KB
29 KB JPG
>>106988355
Two syscalls for each character in the file.......
>>
Is C++ still worth learning? I can't decide between that and Rust. I have decent fluency in python and java...so I'm a shitter rn to be quite honest senpai
>>
>>106988569
NOT RUSTI. MEANT RUBY FUCK STUPID FUCKING TYPO
I AM NOT A TRANNY
>>
>>106988547
he's just optimizing for a machine with 512 bytes of RAM
>>
>>106988465
python is very very very bloated c under the hood but so was the stuff i used
#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *file = fopen("file.txt", "r");
char buffer[1024];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}


>>106988485
yes its hard to benchmark stuff when you print a lot of shit to the terminal there's all sorts of bottlenecks involved that might not be obvious.
>>
in lua this is just
local data = io.open("file.txt"):read()

print(data)
>>
god almighty gave us ram sticks for a reason
int fd = open("test.txt", O_RDONLY);
struct stat st;
fstat(fd, &st);
size_t size = st.st_size;
char* buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
madvise(buf, size, MADV_SEQUENTIAL | MADV_WILLNEED);
write(STDOUT_FILENO, buf, size);
munmap(buf, size);
close(fd);
>>
>>106988645
try increasing the buffer to 1024*1024
>>
>>106988012
this is suboptimal. use this
use std::{fs,io, env};

fn main() {
let p = env::args_os().nth(1).unwrap();
let mut f = fs::File::open(p).unwrap();
let mut o = io::stdout();
io::copy(&mut f, &mut o).unwrap();
}
>>
>>106988236
I paid for casey muratori's substack (I know, I know) and his first little intro goes into Python and C about how even for a simple add function, python will send ~180 unnecessary instructions to the CPU. C sends 1 instruction. end up getting, without other very basic optimizations, 0.800 operations/cycle for C and 0.006 for python or something stupid. The only way to get python fast is to use Cython which is just C.

>>106987909
>std::endl
we are a "\n" board here, partner.
>>
>>106987909
All this cope and yet reality is that C++ and C are fastest languages.

Rust troons compile times are 10 hours straight.
Python performance is literally abysmal it's like trying to generate electricity via your hamster running in it's wheel.
Lua literally worse then Python.
>>
>>106987909
>That C example

It is useless to put a terminal 0, a file can contain null bytes so you shouldn't rely on a terminal zero to bound a char array containing the contents of a file.

There is no reason to omit the b flag when opening the file if you are not to read it line by line with fgets.

Your example should be

struct stuff {
int size;
char contents[];
}

int main()
{
struct stuff * stuff;
FILE* f = fopen(argv[1], "rb"); // add the b
// error handling code
fseek(f, 0, SEEK_END);
// error handling code
long sz = fteel(f);
// error handling code
fseek(f, 0, SEEK_SET);
// error handling code
stuff = malloc(sizeof (struct stuff) + sz);
// error handling code
stuff->size = sz;
fread(&stuff->contents, 1,sz, f);
// error handling code
}
>>
>>>>>>error handling code
>>
>>106988809
malloc just uses mmap if you allicate more than 128kb, so to skip whatever bullshit malloc does, id just use mmap instead
>>
>>106987909
>size_t sz = ftell(f);

Also ftell returns -1 if something goes wrong, good job malloc'ing a zillion bytes if you declare sz as unsigned
>>
>>106988809
>>106988862
if you're using mmap why bother with fopen
>>
>>106988882
This is actually fine, because those zillion bytes are all non-physical and not paged in before they are touched the first time
>>
in C it's just
const char text[] = {
#include "file.txt"
};
>>
File: images(11).jpg (7 KB, 225x225)
7 KB
7 KB JPG
>>106989100
there's no way this compiles
>>
Oh and if you want to print it

printf("%.*", sz, stuff->contents);
>>
>>106989118
it compiles for a single quoted line, will also compile with a two dimensional array if every line in the file is quoted
>>
>>106987909
Okay. You only have to write it once. Put it in a function, and #include it forever after.
>>
>>106988236
>in C you know which system calls are happening
so which system calls exactly are happening when you call fseek on Windows? hmm?
you don't know shit. the C library is a clunky, crippled and extremely limiting wrapper over the real API of your operating system.
>>
>>106987909
cat file.txt
>>
>>106989573
It should be pointer, size and not size, pointer
>>
>>106988584
it's too late anon, you're trans now
>>
>OP intentionally convolutes the process
>surprise_surprise.jpg

#include <fstream>

int main(int argc, char* argv[]) { std::ifstream ifs{argv[1]}; }


>>106991783
He should've just said no when the rustroons knocked at his door. Probably 41%'d by now, I suppose...Sad. Many such cases.
>>
>>106987909
In Lean that is quite simple
def read_file (file_path : String) : IO Unit := do
let io IO.getStdout
let path_to_file := System.FilePath.mk file_path
if (path_to_file.pathExists) then
let handle IO.FS.Handle.mk path_to_file IO.FS.Mode.read
io.putStrLn (handle.readToEnd)
else
io.putStrLn s!"Specified file: {file_path} does not exist!"
pure ()
>>
File: 1755293327545366.jpg (80 KB, 1605x946)
80 KB
80 KB JPG
>>106991991
Sorry forgot, the arrow, so it works now, the best part about Lean is that i can use #eval to evaluate most functions on the fly without need to compile or go to REPL.
def read_file (file_path : String) : IO Unit := do
let io IO.getStdout
let path_to_file := System.FilePath.mk file_path
if (path_to_file.pathExists) then
let handle IO.FS.Handle.mk path_to_file IO.FS.Mode.read
io.putStrLn (handle.readToEnd)
else
io.putStrLn s!"Specified file: {file_path} does not exist!"
pure ()
>>
>>106988236
>confuses the C API with system calls
>>
>>106990395
This is why I just write everything in assembly.
>>
>>106988012
>check for read errors too
In which case data is set to "unable to read file". Which you then have to check against further.
A default value isn't the same as error handling, you disingenious troon.

I hate you zogbots with a passion you wouldn't believe.
Not working for your failed MIC-only Ada replacement.
>>
>>106992099
>a default value
no, that's not what .expect() is

a lot of seething for knowing so little
>>
>>106988693
>unwrap on every line
why even use rust at this point lol
>>
>>106992155
>i require FizzBuzzEnterpriseEdition-like snippets
dumb retard
>>
>>106992195
you are very histronic and also stupid, try going to a gym and having a normal sleep cycle
>>
>>106992147
>i i it totally isnt like that, i i it totally isnt one undescriptive string and the error handling is totally done with 'unable to read file' nothing further needed
I have more respect towards webshitters than towards you zogbots.
A webshitter has to cover all sorts of cases because any request has a hundred different reasony why it could fail and a fucking javascript react dev would laugh you out of the room if you suggest that a "it failed :)" is proper error handling.

And not even do you do that retarded shit, not even do you promote this here, you also act as if its a good thing to do.
>>
>>106987909
#define STB_DS_IMPLEMENTATION
#define STB_DEFINE
#include "stb.h"

int main() {
char* content = stb_file("example.txt");
if (content) printf("%s", content);
stb_free(content);
return 0;
}

If this is a bit too low level/scary bare metal programming just relax op try to take a deep breadth.
>>
>>106992363
>more incoherent screeching
is that your attempt at damage control? further proving that you have no clue what you are talking about?



[Advertise on 4chan]

Delete Post: [File Only] Style:
[Disable Mobile View / Use Desktop Site]

[Enable Mobile View / Use Mobile Site]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.