Unable to open filename passed as command line argument

user1234 user1234 at 12.de
Thu Sep 3 11:12:49 UTC 2020


On Thursday, 3 September 2020 at 10:47:04 UTC, 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?

version b works by accident/UB. You need to null terminate your 
filename if you use the C library functions:

---
void main(string[] args)
{
     FILE* fp = fopen((args[1] ~ '\0').ptr, "r");
     if (!fp) throw new Exception("fopen");
}
---

otherwise what you get as args are D dynamic arrays (a payload 
made of .ptr and .length) so you can use std.file or std.stdio to 
open a file using the "D main" arguments (it's not the like "C 
main").

---
void main(string[] args)
{
     import std.stdio;
     File f = File(args[1], "r");
}
---


More information about the Digitalmars-d-learn mailing list