Re: [Vala] readline from a FileStream?



As far as I can see, glib only has support for reading a whole file at a time, and not line by line. I'm lacking the equivalent of:

#python
for line in f:
    # do something

or

#perl
while(<>) {
    # do something
}

I think it would be nice if the standard library would contain a readline() function that returns a string, something like:

FileStream f = fopen(...);

while(!f.eof()) {
    string s = f.readline();
    # do something with s
}

Would a patch be accepted?

Regards,
Dov

2008/6/8 George Farris <farrisg shaw ca>:
On Sat, 2008-06-07 at 22:57 +0300, Dov Grobgeld wrote:
> Hello,
>
> I've just played around with vala for the first time tonight, and I
> find it very intriguing! I've been previously using gob for most of my
> C coding, but I think that I will try to move to vala as much as
> possible, as soon as I feel comfortable enough with it.
>
> In my efforts to of making sure that I can do simple constructs with
> the language I tried to read a file line by line. The problem is that
> fgets() is mapped quite shallowly as follows:
>
>     public weak string gets (string s, int size);
>
> Thus I need to make sure that s has the requested size before calling
> gets. This is what I eventually came up with:
>
> using GLib;
>
> int main(string[] args) {
>     if (args.length < 2) {
>         stderr.printf("Need name of file!\n");
>         return -1;
>     }
>
>     var f = FileStream.open(args[1],"r");
>     int n = 1000;
>     string s = " ".ndup(n);
>     int line = 0;
>
>     while(true) {
>         f.gets(s, n);
>         if (f.eof())
>             break;
>         stdout.printf("Line %d: %s", line++, s);
>     }
>     return 0;
> }
>
> Is there a more elegant way than by using ndup(n)?
>
> Thanks again!
> Dov

Take a look at Glib, which has Vala bindings.  There is support for
reading and writing files in there I believe.

http://library.gnome.org/devel/glib/2.16/



_______________________________________________
Vala-list mailing list
Vala-list gnome org
http://mail.gnome.org/mailman/listinfo/vala-list



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]