1~5. 다음 코드에 대한 출력 결과를 쓰시오.
1.
#include <stdio.h>
int main() {
FILE *fp = fopen("test.txt", "w");
if (fp != NULL) {
fprintf(fp, "Hello, File!\n");
fclose(fp);
}
fp = fopen("test.txt", "r");
char buffer[20];
if (fp != NULL) {
fscanf(fp, "%s", buffer);
printf("%s\n", buffer);
fclose(fp);
}
return 0;
}
2.
#include <stdio.h>
int main() {
FILE *fp = fopen("data.bin", "wb");
int num = 1234;
fwrite(&num, sizeof(int), 1, fp);
fclose(fp);
fp = fopen("data.bin", "rb");
int read_num;
fread(&read_num, sizeof(int), 1, fp);
printf("%d\n", read_num);
fclose(fp);
return 0;
}
3.
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w");
if (fp != NULL) {
for (int i = 0; i < 3; i++) {
fprintf(fp, "Line %d\n", i + 1);
}
fclose(fp);
}
fp = fopen("output.txt", "r");
char line[20];
if (fp != NULL) {
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);
}
return 0;
}
4.
#include <stdio.h>
int main() {
FILE *fp = fopen("numbers.txt", "w");
if (fp != NULL) {
for (int i = 1; i <= 5; i++) {
fprintf(fp, "%d ", i * 2);
}
fclose(fp);
}
fp = fopen("numbers.txt", "r");
int num;
while (fscanf(fp, "%d", &num) != EOF) {
printf("%d ", num);
}
fclose(fp);
return 0;
}
5.
#include <stdio.h>
int main() {
FILE *fp = fopen("text.txt", "w");
if (fp != NULL) {
fputs("Hello, World!", fp);
fclose(fp);
}
fp = fopen("text.txt", "r");
char buffer[50];
if (fp != NULL) {
fgets(buffer, sizeof(buffer), fp);
printf("%s\n", buffer);
fclose(fp);
}
return 0;
}
정답
(드래그 시 정답이 보입니다.)
1. Hello,
2. 1234
3. Line 1
Line 2
Line 3
4. 2 4 6 8 10
5. Hello, World!
'Study > 정보처리기사' 카테고리의 다른 글
| C언어 Level 9 (0) | 2025.02.20 |
|---|---|
| C언어 Level 8 (0) | 2025.02.20 |
| C언어 Level 6 (0) | 2025.02.20 |
| C언어 Level 5 (0) | 2025.02.20 |
| C언어 Level 4 (0) | 2025.02.20 |