Code Type : C
/*
고급 프로그래밍 및 실습 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);    
}
놀자~ 라고 된 주석 뒷부분 부터 입니다.
텍스트 파일에서 정보를 읽어서 정렬을 한뒤 결과 파일로 저장해주는 프로그램입니다...
파일 입출력은 첫경험이라 덜덜덜 했다죠;;;