---
# System prepended metadata

title: 程式設計(0523)

---

# 程式設計(0523)

## 班級 學號 姓名

### 循序檔的處理

1. 利用電腦亂數建立文字檔案(fwrite.c)，列印程式碼及執行截圖。

```c=
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
int main() {
	srand(time(NULL));
	int i, x;
	FILE * inf;
	inf = fopen("stu.txt", "w");
	for (i = 0; i < N; i++) {
		x = rand() % 101;
		printf("%2d: %3d\n", i, x);
		fprintf(inf, "%d %d\n", i, x);
	}
	fclose(inf);
	return 0;
}
```

2. 讀取上面的文字檔案(fread.c)，列印程式碼及執行截圖。

```c=
#include <stdio.h>
int main() {
	int i, x;
	FILE * inf;
	inf = fopen("stu.txt", "r");
	while (fscanf(inf, "%d %d", &i, &x) != EOF) {
		printf("%2d: %3d\n", i, x);
	}
	fclose(inf);
	return 0;
}
```

3. 檔案處理系統(CRUD)，完成下列五個函數。資料檔(stu.txt)格式如下，列印程式碼及執行截圖。

| No | Score |
| -: | ----: |
|  1 |    85 |
|  2 |    50 |
|  3 |    90 | 
|  4 |    85 |

```c=
#include <stdio.h>
char menu();
void appendRec();
void selectRec();
void updateRec();
void deleteRec();
int main() {
	char c;
	do {
		c = menu();
		switch (c) {
			case 'C':
				appendRec();
				break;
			case 'R':
				selectRec();
				break;
			case 'U':
				updateRec();
				break;
			case 'D':
				deleteRec();
				break;
		}
	} while (c!='Q');
	return 0;
}

char menu() {
	fflush(stdin);
	char c;
	printf("Enter (C) (R) (U) (D) (Q):");
	scanf("%c", &c);
	return c;
}

void appendRec(){
	FILE *fptr;
	int no, score;
	fptr = fopen("stu.txt","a");
	printf("Enter No.:");
	scanf("%d", &no);
	printf("Enter Score:");
	scanf("%d", &score);
	fprintf(fptr, "%d %d\n", no, score);
	fclose(fptr);
}

void selectRec(){
	int n;
	printf("Enter No.:");
	scanf("%d", &n);

	FILE *fptr;
	int no, score;
	fptr = fopen("stu.txt","r");
	while (fscanf(fptr, "%d %d", &no, &score) != EOF) {
		if (no == n){
			printf("Score: %d\n", score);
			break;
		}
	}		
	fclose(fptr);
}

void updateRec(){
	int n, s;
	printf("Enter No.:");
	scanf("%d", &n);
	printf("Enter Score:");
	scanf("%d", &s);

	FILE *fptr, *ftmp;
	int no, score;
	fptr = fopen("stu.txt","r");
	ftmp = fopen("tmp.txt","w");
	while (fscanf(fptr, "%d %d", &no, &score) != EOF) {
		if (no != n){
			fprintf(ftmp,"%d %d\n", no, score);
		} else {
			fprintf(ftmp,"%d %d\n", n, s);
		}
	}
	fclose(ftmp);
	fclose(fptr);
	remove("stu.txt");
	int result = rename("tmp.txt","stu.txt");
}

void deleteRec(){
	int n, s;
	printf("Enter No.:");
	scanf("%d", &n);

	FILE *fptr, *ftmp;
	int no, score;
	fptr = fopen("stu.txt","r");
	ftmp = fopen("tmp.txt","w");
	while (fscanf(fptr, "%d %d", &no, &score) != EOF) {
		if (no != n){
			fprintf(ftmp,"%d %d\n", no, score);
		};
	}
	fclose(ftmp);
	fclose(fptr);
	remove("stu.txt");
	int result = rename("tmp.txt","stu.txt");	
}
```

---

作業繳交方式：寄E-mail
收件人：lenghs@cc.ncue.edu.tw
主旨：程式設計(0523)
附件：程式設計(0523) - HackMD.pdf
內文：本日上課心得(字數不限不得省略)