[c언어] 파일 입출력 연습

2021. 2. 3. 11:46Computer Science/C

 

1. 입력 파일로 input.txt를 작성한다.

 

 

2. 위의 input.txt를 읽어서 모두 대문자로, 그 다음은 모두 소문자로 output.txt 파일에 출력한다.

 

 

코드는 아래와 같다.

 

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

int main(void)
{
    FILE *fp1, *fp2;
    char ch;
    
    fp1 = fopen("input.txt", "w");
    if (fp1 == NULL)
    {
        printf("file open error!\n");
        return 1;
    }
    
    fp2 = fopen("output.txt", "w");
    if (fp2 == NULL)
    {
        printf("file open error!\n");
        return 1;
    }
    
    fprintf(fp1, "Near far\nWherever you are\n");
    fprintf(fp1, "I believe that the heart does go on\n");
    fprintf(fp1, "Once more, you open the door\n");
    fprintf(fp1, "And you're here in my heart\n");
    fprintf(fp1, "And my heart wiil go ono and on\n");
    
    fclose(fp1);
    
    fp1 = fopen("input.txt", "r");
    if (fp1 == NULL)
    {
        printf("file open error!\n");
        return 1;
    }
    
    while((ch = getc(fp1)) != EOF)
    {
        if (islower(ch) != 0)
            ch = toupper(ch);
        else
            ch = ch;
        putc(ch, fp2);
    }
    
    fseek(fp1, 0, SEEK_SET);
    
    fprintf(fp2, "\n");
    while((ch = getc(fp1)) != EOF)
    {
        if (isupper(ch) != 0)
            ch = tolower(ch);
        else
            ch = ch;
        putc(ch, fp2);
    }
    
    fclose(fp1);
    fclose(fp2);
}