2011年1月20日木曜日

Cの FILE IOメモ

ファイルの読み込み
fopen でファイル開いて、
feof(fp) でファイル読み込み、
fgets(str,length-1,fp)でstrを取り込んで
fclose でファイル閉じて終了

#include
#include

int main(void){

FILE *fp;
char str[80];

//fp = fopen("file.txt","r");
if( (fp = fopen("file.txt","r"))==NULL ){
exit(1);
}
while(!feof(fp)){
fgets(str,79,fp);
printf("%s",str);
}
fclose(fp);
}

____________________

ファイルへの書き込み
fopen でファイル開いて、
fprintf でファイルに書き込み、
fclose でファイル閉じて終了

#include

int main(void){

FILE *fp;
int i;
char str[10] = "test";
fp = fopen("file.txt","w");
for(i=0;i<10;i++){
fprintf(fp,"%d:%s\n",i,str);
}
fclose(fp);
}