By GokiSoft.com|
20:19 04/01/2022|
Lập Trình C
[Video] Tìm hiểu về File trong C - Khóa học lập trình C - C2110L
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void writeText01();
void readText01();
void writeBinary01();
void readBinary01();
typedef struct Student_ST {
char name[30];
int age;
} Student;
int main(int argc, char *argv[]) {
// writeText01();
// readText01();
// writeBinary01();
readBinary01();
return 0;
}
void writeText01() {
//B1. Mo ket toi FILE
FILE *fp;
fp = fopen("test01.txt", "w");
if(fp == NULL) {
printf("\nGhi error!!!");
} else {
printf("\nMo file de ghi thanh cong!!!");
//B2. Ghi noi dung vao file
//ghi ky tu
fputc('B', fp);
fputs("\nTRAN VAN B", fp);
fprintf(fp, "\nHo ten: %s, tuoi: %d", "XYZ", 12);
}
//B3. Dong file
fclose(fp);
}
void readText01() {
//B1. Mo ket toi FILE
FILE *fp;
fp = fopen("test01.txt", "r");
if(fp == NULL) {
printf("\nDoc error!!!");
} else {
printf("\nMo file de doc thanh cong!!!\n");
//B2. Doc noi dung tu file
char c;
while((c = fgetc(fp)) != -1) {
printf("%c", c);
}
}
//B3. Dong file
fclose(fp);
}
void writeBinary01() {
//Fake data
Student stdList[2];
int i;
for(i=0;i<2;i++) {
printf("\nNhap ten: ");
fflush(stdin); fflush(stdout);
gets(stdList[i].name);
printf("\nNhap tuoi: ");
scanf("%d", &stdList[i].age);
}
//Luu du lieu vao file
//B1. Mo ket toi FILE
FILE *fp;
fp = fopen("test01.dat", "wb");
if(fp == NULL) {
printf("\nGhi error!!!");
} else {
printf("\nMo file de ghi thanh cong!!!\n");
//B2. ghi noi dung vao file
fwrite(stdList, sizeof(Student), 2, fp);
}
//B3. Dong file
fclose(fp);
}
void readBinary01() {
Student stdList[2];
//B1. Mo ket toi FILE
FILE *fp;
fp = fopen("test01.dat", "rb");
if(fp == NULL) {
printf("\nDoc error!!!");
} else {
printf("\nMo file de doc thanh cong!!!\n");
//B2. doc noi dung vao file
fread(stdList, sizeof(Student), 2, fp);
}
//B3. Dong file
fclose(fp);
//Hien thi du lieu
int i;
for(i=0;i<2;i++) {
printf("\nTen: %s, tuoi: %d", stdList[i].name, stdList[i].age);
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)