Reading and writing binary files
#include <stdio.h>
#define SIZE 20
struct Person{
char name[SIZE];
long id;
float age;
} typedef person_t;
void main(){
person_t p1={"momo", 1111, 23.5}, p2 = {"gogo", 2222, 24.8}, p3, p4;
FILE* f = fopen("persons.bin", "wb");
fwrite(&p1, sizeof(person_t), 1, f);
fwrite(&p2, sizeof(person_t), 1, f);
fclose(f);
f = fopen("persons.bin", "rb");
fread(&p3, sizeof(person_t), 1, f);
fread(&p4, sizeof(person_t), 1, f);
fclose(f);
printf("p3: name: %s\t id: %ld\t age: %.2f\n", p3.name, p3.id, p3.age);
printf("p4: name: %s\t id: %ld\t age: %.2f\n", p4.name, p4.id, p4.age);
}
|
|
|
Reading file into struct
typedef struct person {
char name[20];
int age;
} person;
int main() {
person *people = NULL;
char name[20];
int size, age = 0;
FILE *f = fopen("people.txt", "r");
while (!feof(f)){
scanf("%s %d", name, &age);
people = realloc(people, sizeof(person)(++age)size);
strcpy((people+size-1)->name, name);
(people+size-1)->age = age;
}
fclose(f);
}
|
assume people.txt is formatted like this:
name1 age
name2 age
|
|
Writing to file
#include <stdio.h>
void main()
{
FILE* f = fopen("myFile.txt", "w");
int res;
if (f == NULL){
printf("Failed opening the file. Exiting!\n");
return;
}
fputs("Hello World!\n", f);
fclose(f);
f = fopen("myFile.txt", "a");
fputs("And Good Morning!\n", f);
fclose(f);
}
|
|