/* 고급 프로그래밍 및 실습 10주차 파일 입출력 2002711158 오형탁 */ /*2번 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { FILE *fp; char temp[100]="Hello world"; char temp2[100]; fp=fopen("test.txt","w+"); if (fp==NULL) { printf("FILE open ERROR"); exit(1); } fputs(temp,fp); fgets(temp2,100,fp); printf("%s\n",temp2); fclose(fp); return 0; } /**/ /* 참고 예제 소스 코드 #include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp; char temp[100]="THANK\nYOU\n"; fp=fopen("test.txt","w+"); if(fp==NULL) { printf("FILE open ERORR\n"); exit(1); } printf("before temp = %s\n",temp); fputs(temp,fp); fclose(fp); fp=fopen("test.txt","r"); if(fp==NULL) { printf("FILE open ERORR\n"); exit(1); } fgets(temp,100,fp); printf("after temp = %s\n",temp); fclose(fp); return 0; } /* 놀자 */ #include <stdio.h> #include <stdlib.h> struct BOOK { char name[20]; char auth[20]; int num; int cost; int total; }; void main(void) { struct BOOK book[5]; struct BOOK temp; FILE *fp; int total=0; int idx; int i,j; fp = fopen( "c:\\book.txt" , "r" ); if(fp==NULL) { printf("FILE open ERORR\n"); exit(1); } for(idx=0;idx<=4;idx++) { fscanf(fp,"%s",book[idx].name); fscanf(fp,"%s",book[idx].auth); fscanf(fp,"%d",&book[idx].num); fscanf(fp,"%d",&book[idx].cost); book[idx].total=book[idx].cost*book[idx].num; } fclose(fp); for(i=0;i<=4;i++) { for(j=i+1;j<=4;j++) { if(book[i].total < book[j].total) { temp = book[i]; book[i] = book[j]; book[j] = temp; } } } fp = fopen( "c:\\result.txt" , "w+" ); if(fp==NULL) { printf("OUTPUT FILE open ERORR\n"); exit(1); } fprintf(fp,"----------------------------------------------------------------------------------\n\ Subject | Author | Number | Price | Income \n\ ----------------------------------------------------------------------------------\n"); for(idx=0;idx<=4;idx++) { fprintf(fp,"%20s | %20s | %7d | %10d | %10d\n",book[idx].name,book[idx].auth,book[idx].num,book[idx].cost,book[idx].total); fprintf(fp,"----------------------------------------------------------------------------------\n"); } fclose(fp); }