languages/c
.c file I/O studentDB.bin
och
2022. 3. 23. 12:48
#include<stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#include<string.h>
#define max_num_student 255
enum action {add, fine, Exit};
typedef struct {
int id;
char name[8];
float score;
}student;
int fileopen(FILE** _fp, char* _filename, char* _mode);
int selectaction(void);
int printinfo(student* _info);
int addstudent(FILE* _fp, student* _info);
long finestudent(FILE* _fp, student* _info);
int main(void)
{
FILE* fp = NULL;
student data = { 0 };
char* filename = "studentDB.bin";
fileopen(&fp, filename, "ab+");
while (1)
{
switch (selectaction())
{
case add:
addstudent(fp, &data);
break;
case fine:
if (finestudent(fp, &data) < 0)
printf("Can not fine the student\n");
else
printinfo(&data);
break;
case Exit:
exit(0);
}
}
}
int selectaction(void)
{
int sel = 0;
printf("[%d]add, [%d]find, [%d]exit: ", add, fine, Exit);
scanf("%d", &sel);
return sel;
}
int printinfo(student* _info)
{
printf("%d %s %.2f\n", _info->id, _info->name, _info->score);
}
int addstudent(FILE* _fp, student* _info)
{
printf("Enter id name score : ");
scanf("%d %s %f", &_info->id, &_info->name, &_info->score); getchar();
fseek(_fp, 0, SEEK_END);
fwrite(_info, sizeof(student), 1, _fp);
return 0;
}
long finestudent(FILE* fp, student* info)
{
char name[255] = { 0 };
printf("name: ");
scanf("%s", name); getchar();
//file pointer 처음으로 돌림.
fseek(fp, 0, SEEK_SET);
//size 선언 안 하고 진행하니 error 발생. sizeof 함수가 unsigned int type인데 -붙여서 conversion 일어남.
int size = sizeof(student);
while (!feof(fp))
{
fread(info, size, 1, fp);
if (strcmp(info->name, name) == 0) {
fseek(fp, -size, SEEK_CUR);
return ftell(fp);
}
}
return -1;
}
int fileopen(FILE** _fp, char* _fileName, char* _mode)
{
*_fp = fopen(_fileName, _mode);
if (!*_fp) {
printf("Fail to open - %s\n", _fileName);
return -1;
}
return 0;
}
fseek에 -sizeof(student)를 argument로 전달했는데 sizeof가 unsigned int 이기 때문에 -를 붙일 수가 없음.