0

In Jflex, how does one extract the input filename?

DisplayFilename.jflex:

%%

%class DisplayFilename

%eof{
    /* code to print the input filename goes here */
%eof}

%%

\n { /* do nothing */ }
. { /* do nothing */ }

Commands ran

jflex DisplayFilename
javac DisplayFilename.java
java DisplayFilename someinputfile.txt

desired output:

someinputfile.txt
Heinrich
  • 340
  • 1
  • 4
  • 12
  • The input filename is first available to your `main(String[] args)` as `args[0]`. It is then passed to the parser or scanner. Unclear what you're asking. – user207421 Apr 08 '21 at 00:06
  • I've edited my post to be more specific. I've tried referencing args[0] but with no luck – Heinrich Apr 08 '21 at 11:56

1 Answers1

0

This can be achieved by omitting the %standalone tag at the top of the jflex file. This makes jflex not generate the default main() method and allows the user to set their own custom main() method inside of a %{ %} code segment.

Within this main(), the user can place the original code for the autogenerated main(), but can update to the desired outcome.

Within this context:

%%

%class DisplayFilename

%{
  private static String inputfilename = "";
  
  private static class Yytoken {
    /* empty class to allow yylex() to compile */
  }

  public static void main(String argv[]) {
    if (argv.length == 0) {
      System.out.println("Usage : java DisplayFilename");
    }
    else {
      int firstFilePos = 0;
      String encodingName = "UTF-8";
      for (int i = firstFilePos; i < argv.length; i++) {
        inputfilename = argv[i]; // LINE OF INTEREST
        WC scanner = null;
        try {
          java.io.FileInputStream stream = new java.io.FileInputStream(argv[i]);
          java.io.Reader reader = new java.io.InputStreamReader(stream, encodingName);
          scanner = new WC(reader);
          while ( !scanner.zzAtEOF ) scanner.yylex();
        }
        catch (java.io.FileNotFoundException e) {
          System.out.println("File not found : \""+argv[i]+"\"");
        }
        catch (java.io.IOException e) {
          System.out.println("IO error scanning file \""+argv[i]+"\"");
          System.out.println(e);
        }
        catch (Exception e) {
          System.out.println("Unexpected exception:");
          e.printStackTrace();
        }
      }
    }
  }
%}


%eof{
    /* code to print the input filename goes here */
      System.out.println(inputfilename);
%eof}

%%

\n { /* do nothing */ }
. { /* do nothing */ }
Heinrich
  • 340
  • 1
  • 4
  • 12