www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - strange file behaviour

reply maarten van damme <maartenvd1994 gmail.com> writes:
hello,
I wrote this little test:
import std.stdio;

void main(){
auto testfile=new File("test.txt");
 foreach(string line;lines(testfile))
writeln(line);
}
and get as error
src\main.d(6): Error: constructor std.stdio.lines.this (File f, dchar
terminator = cast(dchar)'\x0a') is not callable using argument types (File*)
src\main.d(6): Error: cannot implicitly convert expression (testfile) of
type File* to File

Why?
I've also noticed the argument to lines in the example was a stream but now
it claims to be a File. when I feed it a File it complains it is given a
*File... what am I doing wrong?
Mar 04 2012
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 03/04/2012 11:43 AM, maarten van damme wrote:
 hello,
 I wrote this little test:
 import std.stdio;

 void main(){
 auto testfile=new File("test.txt");

That is a pointer but lines() takes a File. Either construct testfile like this: auto testfile = File("test.txt"); or use lines(*testfile) in the foreach loop.
   foreach(string line;lines(testfile))
 writeln(line);
 }
 and get as error
 src\main.d(6): Error: constructor std.stdio.lines.this (File f, dchar
 terminator = cast(dchar)'\x0a') is not callable using argument types 

(File*)
 src\main.d(6): Error: cannot implicitly convert expression (testfile) of
 type File* to File

 Why?
 I've also noticed the argument to lines in the example was a stream 

but now
 it claims to be a File. when I feed it a File it complains it is given a
 *File... what am I doing wrong?

Just a reminder that "If line has type char[], wchar[], dchar[], the line's con­tent will be reused (over­writ­ten) across reads.": http://dlang.org/phobos/std_stdio.html#lines Ali
Mar 04 2012
parent reply maarten van damme <maartenvd1994 gmail.com> writes:
thank you for helping me out.
I do not really understand why new File creates a pointer to a file object.
does new struct() creates a pointer to that newly created struct?
Mar 04 2012
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 03/04/2012 01:35 PM, maarten van damme wrote:
 thank you for helping me out.
 I do not really understand why new File creates a pointer to a file 

object.
 does new struct() creates a pointer to that newly created struct?

Yes. new returns a pointer for structs and non-reference fundamental types. For reference types like classes and arrays, it returns a reference to the actual variable: struct S {} class C {} void main() { /* Value types */ int * ip = new int; double * dp = new double; S * sp = new S; /* Reference types */ C class_variable = new C; int[] slice = new int[10]; } Ali
Mar 04 2012