C언어 콘서트

C언어 콘서트 12장 파일 입출력 LAB 도전문제

렛쓰기릿 2023. 9. 2. 17:31

1. 469P 텍스트 파일 복사하기 ( 숫자와 알파벳의 아스키코드 범위를 가진 문자들만 복사됨 )

#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h> //rand(), srand()
#include <time.h>  //time()
#include <string.h> //strcmp()문자열비교
#include <math.h> // sqrt

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, "w")) == NULL)	{
		fprintf(stderr, "복사 파일 %s를 열 수 없습니다.\n", file2);
		exit(1);
	}

	int c;
	while ((c = fgetc(fp1)) != EOF) {
		if ((48 <= c && c <= 57) || (65 <= c && c <= 90) || (97 <= c && c <= 122))
			fputc(c, fp2);
	}
	fclose(fp1);
	fclose(fp2);
	return 0;
}

 

2. 성적을 파일에 기록하기

#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h> //rand(), srand()
#include <time.h>  //time()
#include <string.h> //strcmp()문자열비교
#include <math.h> // sqrt

int main(void)
{
	FILE* fp;
	char ch;
	char name[30];
	int number, score;


	fp = fopen("scores.txt", "w");
	if (fp == NULL) {
		printf("성적 파일 scores.txt를 열 수 없습니다.\n");
		exit(0);
	}

	do {
		printf("\n학번 : ");
		scanf("%d", &number);
		printf("이름 : ");
		scanf("%s", name);
		printf("성적 : ");
		scanf("%d", &score);

		fprintf(fp, " %d %s %d \n", number, name, score);
		printf("데이터 추가를 계속? (y/n) : ");
		ch = _getche();
	} while (ch != 'n');

	fclose(fp);
	return 0;
}

 

3. 479P 이미지 파일 읽어서 표시하기 (d드라이브, txt파일들 생성되던 위치에 둘 다 lena파일 넣어놨는데도 콘솔에서 프린트 안됨) 이유 모르겠

#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h> //rand(), srand()
#include <time.h>  //time()
#include <string.h> //strcmp()문자열비교
#include <math.h> // sqrt
#include <windows.h>

int main(void)
{
	HDC hdc = GetWindowDC(GetForegroundWindow());

	FILE * fp = fopen("d:\\lena(256x256).raw", "rb");
	if (fp == NULL) {
		printf("lena.raw파일을 열 수 없습니다.");
		exit(1);
	}
	char image[256][256];
	fread(image, 1, 256 * 256, fp);
	fclose(fp);

	int r, c;
	for (r = 0; r < 256; r++) {
		for (c = 0; c < 256; c++) {
			int red = image[r][c];
			int green = image[r][c];
			int blue = image[r][c];
			SetPixel(hdc, c, r, RGB(red, green, blue));
		}
	}
}