반응형
1. 구조체 파일이 2진 파일로 저장되어 있는 경우에 읽어들여서 화면에 출력하는 프로그램
#include <stdio.h> #include <stdlib.h> #include <string.h> struct mydata { char name[10]; int clang, vb, tot; double avg; }; int main() { FILE* inp; mydata person; //파일 쓰기 fopen_s(&inp, "bin1.bin", "wb"); if (inp == NULL) { printf("파일을 열 수 없습니다. \n"); return 0; } strcpy_s(person.name, 10, "son"); person.clang = 10; person.vb = 13; person.tot = person.clang + person.vb; person.avg = person.tot / 2.0; fwrite(&person, sizeof(person), 1, inp); //fprintf(inp, "%10s %3d %3d %3d %6f\n", person.name, person.clang, person.vb, person.tot, person.avg); fclose(inp); //파일 읽기 fopen_s(&inp, "bin1.bin", "rb"); if (inp == NULL) { printf("파일을 열 수 없습니다. \n"); return 0; } //fscanf_s(inp, "%10s %3d %3d %3d %6lf\n", person.name,10, &person.clang, &person.vb, &person.tot, &person.avg); while (true) { fread(&person, sizeof(person), 1, inp); if (feof(inp) != 0) { break; } printf("%10s %3d %3d %3d %6.2f\n", person.name, person.clang, person.vb, person.tot, person.avg); } fclose(inp); }
2. (1) gets()와 fprintf()를 사용하여 이름, 국어 성적, 영어 성적 3개의 데이터를
18바이트를 1블록으로 하는 3블록의 데이터를 키보드로 입력받아 "test1.dat"파일에 저장한다.
(2) 생성된 파일 "test1.dat"를 18바이트*3블록 = 54바이트를 읽어 "test.dat"에 2블록만 저장한다.
#include <stdio.h> #include <stdlib.h> int main() { char name[10], kor[3], eng[3]; FILE* fp; fopen_s(&fp, "test1.dat", "wb"); if (fp == NULL) { printf("파일을 만드는데 실패했습니다. \n"); return 0; } for (int iCnt = 0; iCnt < 3; iCnt++) { printf("\n"); printf("name : "); gets_s(name); printf("korean : "); gets_s(kor); printf("English : "); gets_s(eng); fprintf(fp, "%10s%4s%4s", name, kor, eng); } fclose(fp); FILE* fp1; FILE* fp2; char buf[91]; fopen_s(&fp1, "test1.dat", "rb"); if (fp == NULL) { printf("파일을 여는데 실패했습니다. \n"); return 0; } fopen_s(&fp2, "test2.dat", "wb"); if (fp == NULL) { printf("파일을 여는데 실패했습니다. \n"); return 0; } while (fread(buf, 18, 3, fp1) != NULL) { fwrite(buf, 18, 2, fp2); fwrite(buf, 18, 2, stdout); } _fcloseall(); }
3. 5명의 이름과 주소를 레코드 단위의 랜덤 파일 "test,dat"로 디스크에 저장하고 파일의 크기를 나타내는 프로그램을 작성하세요.
#include <stdio.h> #include <stdlib.h> #define REC 44L int main() { FILE* fp; char name[10], addr[34]; long offset; fopen_s(&fp, "test.txt", "w"); if (fp == NULL) { printf("파일을 만드는데 실패했습니다. \n"); return 0; } for (int iCnt = 0; iCnt < 3; iCnt++) { printf("record number : %d \n", iCnt); printf("Name :"); gets_s(name); printf("Address : "); gets_s(addr); printf("\n"); offset = iCnt * REC; //레코드의 위치 계산 fseek(fp, offset, SEEK_SET); //레코드 단위로 랜덤파일 지정 fprintf(fp, "%-10s%-34s", name, addr); } fseek(fp, 0L, SEEK_END); printf("the size of the file is %d", ftell(fp)); fclose(fp); }
4. rewind를 사용하여 버퍼에 남아있는 내용을 제거하는 프로그램
#include <stdio.h> int main() { int c; while ((c = getchar()) != EOF) { switch (c) { case 'a': printf("America \n\n"); break; case 'b': printf("canada \n\n"); break; case 'c' : printf("Korea \n\n"); break; default: printf("--End-- \n\n"); break; } rewind(stdin); //없으면 남아있는 '\n'값 때문에 루프를 두번 실행한다. } }
//C는 일단 여기서 완료!
반응형