BashでC ++ファイルを読み取る方法

BashでC ++ファイルを読み取る方法

次のようなファイルがあるとしましょう。

[inp] // This is the file name
2
1 2 3
5 7 9

これは、次のコードを使用してC ++で読み取ることができます。

main()
{
    freopen("inp","r",stdin); // Redirect stdin to file, while open the file in read mode
    int n; cin >> n; // A variable to get the numbers of lines. n = 2 in this case and the file cursor is after the first line
    for (int i = 0; i < n; i++) // n-time loop
    {
        int a, b, c; // 3 numbers to save 3 values on each line
        cin >> a >> b >> c; // Read the numbers from each line. The file cursor after each loop is at the end of a line
        doSomething(a, b, c); // Do something with 3 read variables.
    }
}

これは、C ++でファイルカーソルを制御できることを意味します。 Bashの私のコード:

inp="./inp" # file name
n=$(head -1 $inp) # Get numbers of line to read
for i in {1..$n}
do
    echo * | head -1 $inp | awk '{print $1;}' < $inp
done

各行で1と5だけを取得するのではなく、私が得た出力は3行で2 1 5です。だから私たちはbashでファイルカーソルを制御できないと思います。解決策はありますか?

ベストアンサー1

はい、Bashからファイルを読み取るときにカーソルを制御できますが、それを行うには、C / C ++<と同じまたは類似の単一ファイルリダイレクト操作()を使用する必要があります。open()

以下は、前述のC ++コードとほぼ同じbashのコードです。

do_something () {
  local linenumber
  linenumber=$1
  shift
  echo "doing something with args $* from line $linenumber"
}

inp="./inp" # file name

{ read numlines
  for ((i = 1; i <= numlines; i++)); do
    read a b c
    do_something "$i" "$a" "$b" "$c"
  done
} <"$inp"

ご覧のとおり、リダイレクト<"$inp"は1つだけです。そして、ファイル(この場合はブロック内)から読み取られるすべてのコマンドは、{ ... }最後の操作後にファイルが残ったカーソルの場所を含む、対応するファイル記述子を共有します。

おすすめ記事