쉽게 풀어쓴 C언어 EXPRESS(개정 3판) - Chapter 16-1

1.

#include <stdio.h>
#include <stdlib.h>

int main(void) {

FILE* fp1, * fp2;

char file1[100], file2[100];

printf("첫번쨰 파일 이름: ");
scanf("%s", file1);

printf("두번째 파일 이름: ");
scanf("%s", file2);

if ((fp1 = fopen(file1, "r")) == NULL) {

fprintf(stderr, "원본 파일 %s을 열 수 없습니다.\n", file1);
exit(1);
}

// 두번째 파일을 읽기 모드로 연다.

if ((fp2 = fopen(file2, "r")) == NULL) {

fprintf(stderr, "복사 파일 %s을 열 수 없습니다.\n", file2);
exit(1);
}

// 첫 번째 파일과 두 번째 파일을 비교

while (1) {

int c1 = fgetc(fp1);
int c2 = fgetc(fp2);

if (c1 == EOF || c2 == EOF)
break;

if (c1 != c2) {

printf("두 파일은 서로 다릅니다.\n");
return 0;
}
}

printf("두 파일은 서로 같습니다.\n");

fclose(fp1);
fclose(fp2);

return 0;
}

2.

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

int main(void) {

FILE* fp1, * fp2;

char file1[100], file2[100];
char c;

printf("첫번쨰 파일 이름: ");
scanf("%s", file1);

printf("두번째 파일 이름: ");
scanf("%s", file2);

if ((fp1 = fopen(file1, "r")) == NULL) {

fprintf(stderr, "파일 %s을 열 수 없습니다.\n", file1);
exit(1);
}

// 두번째 파일을 읽기 모드로 연다.

if ((fp2 = fopen(file2, "w")) == NULL) {

fprintf(stderr, "파일 %s을 열 수 없습니다.\n", file2);
exit(1);
}

// 첫 번째 파일과 두 번째 파일을 비교

while (1) {

c = fgetc(fp1);

if (c == EOF)
break;

fputc(toupper(c), fp2);
}

fclose(fp1);
fclose(fp2);

return 0;
}

3.

#include <stdio.h>

#define SIZE 100

int main(void) {

int buffer[SIZE];

FILE* fp = NULL;
FILE* fp1 = NULL;

int i;
int count;

char file1[100], file2[100];

printf("원본 파일 이름: ");
scanf("%s", file1);

printf("복사 파일 이름: ");
scanf("%s", file2);

fp = fopen(file1, "rb");

if (fp == NULL) {

fprintf(stderr, "파일을 열 수 없습니다.");
return 1;
}

fp1 = fopen(file2, "wb");

if (fp1 == NULL) {

fprintf(stderr, "파일을 열 수 없습니다.");
return 1;
}

while ((count = fread(buffer, sizeof(char), SIZE, fp)) != 0) {

fwrite(buffer, sizeof(char), count, fp1);
}

fclose(fp);
fclose(fp1);

return 0;
}

4.

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

int main(void) {

FILE* fp1, * fp2;

char file1[100], file2[100];
char buffer1[1000], buffer2[1000];

printf("첫번쨰 파일 이름: ");
scanf("%s", file1);

printf("두번째 파일 이름: ");
scanf("%s", file2);

if ((fp1 = fopen(file1, "r")) == NULL) {

fprintf(stderr, "원본 파일 %s을 열 수 없습니다.\n", file1);
exit(1);
}

if ((fp2 = fopen(file2, "r")) == NULL) {

fprintf(stderr, "복사 파일 %s을 열 수 없습니다.\n", file2)
exit(1);
}

char* p1 = fgets(buffer1, 1000, fp1);
char* p2 = fgets(buffer2, 1000, fp2);

if (p1 == NULL || p2 == NULL)
break;

if (strcmp(buffer1, buffer2) != 0) {

printf("<< %s", buffer1);
printf(">> %s", buffer2);
}
}

fclose(fp1);
fclose(fp2);

return 0;
}

댓글

이 블로그의 인기 게시물

쉽게 풀어쓴 C언어 EXPRESS(개정 3판) - Chapter 10-3

쉽게 풀어쓴 C언어 EXPRESS(개정 3판) - Chapter 13-2