-1

I'm looking for a way to read multiple files in Vala. There's one example running throughout the internet about reading all files in a folder and sorting them by their type, but I couldn't make something out of that,still trying though. I'm talking about: http://www.valadoc.org/#!api=glib-2.0/GLib.Dir and https://wiki.gnome.org/Projects/Vala/GIOSamples, mostly.

Inside my folder, I have a bunch of files plus my vala program. I need to read all of the files in that folder with a certain filename extension. e.g. Read all .txt files until there's not more .txt files in that folder.

Many thanks!

John Smith
  • 53
  • 1
  • 8

1 Answers1

1

I would do it in this way...

void main( )
{
  string dir = ".";
  Dir d;
  try
  {
    d = Dir.open( dir );
  }
  catch ( FileError e )
  {
    stderr.printf( "Could not open %s! %s", dir, e.message );
    return;
  }
  unowned string? name;
  while ( ( name = d.read_name( ) ) != null )
  {
    string path = Path.build_filename( dir, name );
    if ( name.down( ).has_suffix( ".txt" ) && FileUtils.test( path, FileTest.IS_REGULAR ) )
    {
      FileStream? f = FileStream.open( path, "r" );
      if ( f == null )
      {
        stderr.printf( "Error opening %s for reading! %d: %s\n", path, GLib.errno, GLib.strerror( GLib.errno ) );
        return;
      }
      /* Read contents from f... */
    }
  }
}