Unable to open filename passed as command line argument

drug drug2004 at bk.ru
Thu Sep 3 11:04:33 UTC 2020

On 9/3/20 1:47 PM, Curious wrote:
> Given the following:
> =====a======
> void main(string[] args)
> {
>      FILE* fp = fopen(args[1].ptr, "r");
>      if (!fp) throw new Exception("fopen");
> }
> =====b======
> void main(string[] args)
> {
>      FILE* fp = fopen(args[1].dup.ptr, "r");
>      if (!fp) throw new Exception("fopen");
> }
> Why does a fail but b succeed?

try `toStringz`:
import std.string : toStringz;

void main(string[] args)
      FILE* fp = fopen(args[1].toStringz, "r");
      if (!fp) throw new Exception("fopen");
The reason is that args are D strings (that contains no terminating 0) 
but `fopen` gets C string (null terminated) so your `a` variant fails 
because the filename becomes wrong as there is no terminating 0. Your 
`b` variant works in fact accidentally because after duplication in new 
memory after filename 0 appears due to random reason (for example all 
that memory area zeroed by allocator).

More information about the Digitalmars-d-learn mailing list