Manually allocating a File

Uknown sireeshkodali1 at gmail.com
Tue Feb 20 15:21:59 UTC 2018


On Tuesday, 20 February 2018 at 14:56:54 UTC, Chris M. wrote:
> I'm doing this mainly for experimentation, but the following 
> piece of code gives all sorts of errors. Hangs, segfaults or 
> prints nothing and exits
>
> import std.stdio;
> import core.stdc.stdlib;
>
> void main()
> {
>     auto f = cast(File *) malloc(File.sizeof);
>     *f = File("test.txt", "r");
>     (*f).readln.writeln;
>     // freeing is for chumps
> }
>
> I could have sworn I've done something similar recently and it 
> worked, unfortunately I can't remember what the case was.
>
> This is what gdb gave me on a segfault
>
> Program received signal SIGSEGV, Segmentation fault.
> 0x00007ffff7a56c32 in 
> _D2rt5minfo__T17runModuleFuncsRevSQBgQBg11ModuleGroup8runDtorsMFZ9__lambda1ZQCkMFAxPyS6object10ModuleInfoZv ()
>    from /usr/lib64/libphobos2.so.0.78
>
> So it looks like it's reaching the end of main. Past that I 
> can't tell what's going on. Ideas?

File * is a C standard library type. You mixed the C standard 
library and D standard library in a way that would not work.

The correct way to initialize a File*:

void main()
{
     import core.stdc.stdlib;
     auto F = fopen("test.txt", "r");
     scope_exit(fclose(f));

     //Reading from the file:

     char[100] str;
     fgets(&s[0], s.length, f);
}

Honestly speaking though you should avoid using the C library 
when you can use th D standard library.

You can read more on the C standard library and how to use it 
here:
http://en.cppreference.com/w/c/io


More information about the Digitalmars-d-learn mailing list