D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 4629 - BufferedFile.printf() wants char[] as first argument
Summary: BufferedFile.printf() wants char[] as first argument
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: x86 Windows
: P2 normal
Assignee: Andrei Alexandrescu
URL:
Keywords: rejects-valid
Depends on:
Blocks:
 
Reported: 2010-08-11 19:38 UTC by bearophile_hugs
Modified: 2012-04-24 18:29 UTC (History)
3 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2010-08-11 19:38:30 UTC
Using dmd 2.048 on this code:


import std.stream: BufferedFile, FileMode;
void main() {
    auto f = new BufferedFile("testfile.t", FileMode.Out);
    f.printf("%d\n", 10);
    f.close();
}


It shows the errors:
test.d(4): Error: function std.stream.Stream.printf (char[] format,...) is not callable using argument types (string,int)
test.d(4): Error: cannot implicitly convert expression ("%d\x0a") of type string to char[]


This gives no errors:
f.printf(cast(char[])"%d\n", 10);
Comment 1 Andrej Mitrovic 2010-08-29 18:42:59 UTC
Casting a string literal to a char[] is esentially undefined behavior. If you need a char[] out of a string literal, use .dup:

import std.stream: BufferedFile, FileMode;

void main() 
{
    auto f = new BufferedFile("testfile.t", FileMode.Out);
    
    f.printf("%d\n".dup, 10);
    f.close();
}

I'm guessing printf takes a char[] due to it's C heritage? So far I've seen a lot of D1 code that uses char[] and when porting it to D2 one needs to either change all declarations/arguments to use a string, or at the very least use .dup when passing string literals to functions taking char[].


(In reply to comment #0)
> Using dmd 2.048 on this code:
> 
> 
> import std.stream: BufferedFile, FileMode;
> void main() {
>     auto f = new BufferedFile("testfile.t", FileMode.Out);
>     f.printf("%d\n", 10);
>     f.close();
> }
> 
> 
> It shows the errors:
> test.d(4): Error: function std.stream.Stream.printf (char[] format,...) is not
> callable using argument types (string,int)
> test.d(4): Error: cannot implicitly convert expression ("%d\x0a") of type
> string to char[]
> 
> 
> This gives no errors:
> f.printf(cast(char[])"%d\n", 10);
Comment 2 SomeDude 2012-04-21 15:19:12 UTC
Compiles on 2.059