ファイルの読み書き

  • cでのファイル操作
  • こちらを参照
    • 1. まずファイルを開く
FILE* fp
fp = fopen("ファイル名", "モード")
    • 2. 読み込むとき
fscanf(fp, )
    • 3. 書き出すとき
fprintf(fp, )
    • 4. 最後にファイルを閉じる
fclose(fp)
  • これらを使ってファイルの書き出し
    • "w"モードでファイル"wmode.txt"に書き出す
/*write.c*/
#include <stdio.h>

int main(void)
{
	FILE* fp;
	fp = fopen("wmode.txt","w");
	if (fp == NULL) {return 1;}
	fprintf(fp,"1.1 2.1 3.1\n");
	fclose(fp);
    return 0;
}
  • ファイルの読み込み
    • "r"モードで"wmode.txt"を読み込む
/*read.c*/
#include <stdio.h>

int main(void)
{
	FILE* fp;
	float n[10];
	char input[]="wmode.txt";
	
	fp = fopen(input,"r");
	if (fp == NULL) return 1;
	fscanf(fp,"%f %f %f",&n[0],&n[1],&n[2]);	
	fclose(fp);
	printf("%f %f %f",n[0],n[1],n[2]);

    return 0;
}
  • ファイルの読み書きとコマンドライン引数を合わせる
    • ファイル argv[1] を読み込んで、ファイル argv[2] に書き出す
    • n[]はファイルから読み込んだもの
    • xはコマンドから与えた argv[3]
/*readwrite.c*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	float x;
	float n[10];
	x = atof(argv[3]);
	FILE* fp1;
	fp1 = fopen(argv[1],"r");
	if (fp1 == NULL) return 1;
	
	fscanf(fp1,"%f %f %f",&n[0],&n[1],&n[2]);	
	fclose(fp1);
	
	FILE* fp2;
	fp2 = fopen(argv[2],"w");
	printf("%f %f %f\n",n[0]*x,n[1]*x,n[2]*x);
	printf("x is %f\n",x);
	fprintf(fp2,"%f %f %f",n[0]*x,n[1]*x,n[2]*x);
	fclose(fp2);
	
    return 0;
}
  • 実行するには
gcc reawrite.c -o readwrite
./readwrite wmode.txt readwrite.txt 2.5
  • 実行すると
> ./readwrite wmode.txt readwrite.txt 2.5
2.750000 5.250000 7.750000
x is 2.500000