0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++でファイルを通した入出力をしたい(備忘録1)

Last updated at Posted at 2024-05-04

演習の授業でつまづいたところをまとめた。

C++でファイルを通した入出力

出力ファイル名に変数を含む時のコード例(fprintfを利用する方法)

先にディレクトリでdataを作っておく必要がある。
ファイルへの出力はdata/filexxx.dat(xxxには3桁でゼロ埋めをする)ときを考える。

using namespace std;

int main(){
  int n = 100;

  // def of name of file(s)
  char filename[20] = "data/file";
  char extension[5] = ".dat";
  char filepath[25];

  for(int i = 1; i <= n; i++){
    sprintf(filepath, "%s%03d%s", filename, i, extension);

    // make file(s)
    FILE *file = fopen(filepath, "w");

    // output to file(s)
    fprintf(file, "hogehoge \n");
    fprintf(file, "03%d\n", i);

    // close file(s)
    fclose(file);
  }
  return 0;
}

これを実行すると,data/file001.datからdata/file100.datまでの100ファイルが生成されて,その中には,たとえばdata/filexxx.datには

hogehoge
xxx

と記入されて出力されている。

出力ファイル名に変数を含む時のコード例(ofstreamを利用する方法)

上のコードでfor文の内部を以下のように書き換えると同じ出力を得ることができる。

for(int i = 1; i <= n; i++){
  sprintf(filepath, "%s%03d%s", filename, i, extension);
  
  ofstream ofs;
  ofs.open(filepath);
  
  // output to file(s)
  ofs << "hogehoge" << endl;
  ofs << setfill('0') << right << setw(3) << i << endl;
  
  ofs.close();
}

Gnuplotで線分を表示する方法

plot "-"
0.0, 0.0
1.0, 1.5
e

とすると(0, 0)(1, 1.5)を結ぶ線分が出力される

pngを統合してgifを作る方法

> convert $(ls *.png | sort -V) out.gif

(注) lsでpngファイルを探して,sortを行い,順番通りに並べる。それをconvertに渡してout.gifを作っている。
(参)convertを使うと,WARNING: The convert command is deprecated in IMv7, use "magick"という表示が出てくるので,

>  magick $(ls *.png | sort -V) out.gif 

とした方がいいかもしれない

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?