www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - inputting functions for std.stdio

std.stdio doesn't really have <i>inputting</i> functions yet, so I wrote some:

<pre>
void[] readx(FILE *fp, int newline)
{
byte c;
byte[] buf;

for(int i = 0;c != '\n';i++)
{
c = fgetc(fp);
if(c == '\n')
{}
else
{
buf.length = i+1;
buf[i] = c;
}
}
// add the newline
if(newline)
{
buf.length = buf.length + 1;
buf[buf.length-1] = '\n';
}
return buf;
}

/* read characters from stdin, but
don't return the newline */
void[] readf()
{
return readx(stdin, 0);
}
/* read characters from stdin, and
return the newline */
void[] readfln()
{
return readx(stdin, 1);
}
/* read characters from fp, but
don't return the newline */
void[] freadf(FILE *fp)
{
return readx(fp, 0);
}
/* read characters from fp, and
return the newline */
void[] freadfln(FILE *fp)
{
return readx(fp, 1);
}
</pre>

I followed the same style that the writef()-related functions use. I think that
readf()/freadf() are an excellent replacements for the C fgets() function,
because with readf() and freadf() you don't need to specify a size.

Usage (should be obvious, but I'll give one anyways):
<pre>
import std.stdio; // assuming that readf() is in the next phobos release

int main()
{
writef("NAME: ");
char[] name = cast(char[])readf();
writefln("Hello, ", name, "!");

FILE *fp = fopen("whatever", "r");
char[] line = cast(char[])freadf(fp);
writefln("Line from whatever: ", line);
return 0;
}
</pre>
Aug 18 2004