20131007【C言語】fprintfとfscanfを使う

お題

fprintfとfscanfを使う。

プログラム処理概要

コマンドラインで指定されたファイルに固定値を書き込み、

そのファイルを読み込んで画面に表示する。

ソース

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
 FILE *fp;
 double ld;
 int d;
 char str[80];

 /* Check arg count */
 if (argc != 2) {
  fprintf(stderr, "Usage : <Program Name> <File Name>.\n");
  exit(1);
 }

 /* Open file for output */
 if *1 == NULL) {
  fprintf(stderr, "Cannot open %s.\n", argv[1]);
  exit(1);
 }

 fprintf(fp, "%f %d %s\n", 12345.342, 1908, "hello");
 fclose(fp);

 /* Open file for input */
 if *2 == NULL) {
  fprintf(stderr, "Cannot open %s for read.\n", argv[1]);
  exit(1);
 }

 fscanf(fp, "%lf%d%s", &ld, &d, str);
 fprintf(stdout, "%f %d %s\n", ld, d, str);
 fclose(fp);
 
 exit(0);
}

実行結果

# ./a.out hoge.txt
12345.342000 1908 hello
# cat hoge.txt
12345.342000 1908 hello

*1:fp = fopen(argv[1], "w"

*2:fp = fopen(argv[1], "r"