Лекция 22 - Файлове 2
Код от час
А клас
Б клас
В клас
txt_files.c
#include <stdio.h>
#include <string.h>
struct student_t {
char name[50];
float score;
int is_late;
};
int main(int argc, char** argv) {
struct student_t class[10];
//printf("argc: %d argv[0]: %s\n", argc, argv[0]);
if(argc > 1) {
FILE* file = fopen(argv[1], "r");
char buff[50];
int i = 0;
while(fgets(buff, 50, file) != NULL) {
//printf("%s ", buff);
puts(buff);
buff[strlen(buff) - 1] = '\0';
strcpy(class[i].name, buff);
fscanf(file, "%f", &class[i].score);
fscanf(file, "%d", &class[i].is_late);
fgetc(file);
//fflush(file);
i++;
}
fclose(file);
for(int j=0; j<i; j++) {
printf("[%d] %s %f %d\n", j, class[j].name, class[j].score, class[j].is_late);
}
} else {
strcpy(class[0].name, "Georgi");
class[0].score = 3.4;
class[0].is_late = 1;
strcpy(class[1].name, "Alexander");
class[1].score = 4.3;
class[1].is_late = 1;
strcpy(class[2].name, "Daniel");
class[2].score = 4;
class[2].is_late = 0;
FILE* file = fopen("./out.txt", "w");
for(int i=0; i<3; i++) {
fputs(class[i].name, file);
fprintf(file, "\n%f\n%d\n", class[i].score, class[i].is_late);
}
fclose(file);
}
return 0;
}
bin_files.c
#include <stdio.h>
#include <string.h>
struct student_t {
char name[50];
float score;
int is_late;
};
int main(int argc, char** argv) {
struct student_t class[10];
if(argc > 1) {
FILE* file = fopen(argv[1], "rb");
int i = 3;
fseek(file, 0, SEEK_END);
int bite_count = ftell(file);
//fseek(file, 0, SEEK_SET);
rewind(file);
i = bite_count / sizeof(struct student_t);
fread(class, sizeof(struct student_t), i, file);
fclose(file);
for(int j=0; j<i; j++) {
printf("[%d] %s %f %d\n", j, class[j].name, class[j].score, class[j].is_late);
}
} else {
strcpy(class[0].name, "Georgi");
class[0].score = 3.4;
class[0].is_late = 1;
strcpy(class[1].name, "Alexander");
class[1].score = 4.3;
class[1].is_late = 1;
strcpy(class[2].name, "Daniel");
class[2].score = 4;
class[2].is_late = 0;
FILE* file = fopen("./out.bin", "wb");
fwrite(class, sizeof(struct student_t), 3, file);
/*int i = 123;
fwrite(&i, sizeof(int), 1, file);*/
fclose(file);
}
return 0;
}