I am outputting a lot of tex tables as raw files and then merge them into one ordered tex document using an automated procedure. The code below works, it stores all files in the folder in the local `files' and then loops over these files in the middle of a file write.

The problem is the tables are not the order I want to. And that even though they are named quite simply table_1 table_2 etc. This order seems to be somewhat random as it changes between running codes.

Is any of these two options (or another) feasible?
1. Sort the files in the files in the folder from within stata (presuming the local dir adheres to that order)
2. Sort the elements within the files local after creating it?

Here is code of the second step. To use this you would need some .tex files in a folder defined by $output.

Code:
cap erase "$output/all_tables.tex"
local files : dir "$output" files "*.tex", respectcase

cap file close myfile
file open myfile using "$output/all_tables.tex", write replace
    file write myfile ///
    "\documentclass{article}"    _n ///
    "\textwidth=14cm"            _n ///
    "\begin{document}"            _n ///
    foreach file in `files' {
        file write myfile ///
        "\begin{table}[ht!]"    _n ///
        "\centering"            _n ///
        "\input{`file'}"        _n ///
        "\end{table}"            _n ///
        "\clearpage"            _n ///
    }
    file write myfile ///
    "\end{document}"            _n
file close myfile