ch05: new chapter

This commit is contained in:
Luciano Ramalho
2020-02-19 00:11:45 -03:00
parent b74ea52ffb
commit 1df34f2945
25 changed files with 640 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
To compile `metro_write.c` on MacOS 10.14 with XCode:
$ clang metro_write.c -o metro
Output:
$ xxd metro_areas.bin
00000000: e207 0000 546f 6b79 6f00 0000 0000 0000 ....Tokyo.......
00000010: 0000 0000 0000 0000 4a50 01e7 1158 274c ........JP...X'L
00000020: df07 0000 5368 616e 6768 6169 0000 0000 ....Shanghai....
00000030: 0100 0000 0e00 0000 434e 0000 f8a0 134c ........CN.....L
00000040: df07 0000 4a61 6b61 7274 6100 0000 0000 ....Jakarta.....
00000050: 0000 0000 0000 0000 4944 0000 bcc5 f14b ........ID.....K
$ python3 metro_read.py
2018 Tokyo, JP 43,868,228
2015 Shanghai, CN 38,700,000
2015 Jakarta, ID 31,689,592

BIN
05-record-like/struct/metro Executable file

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,15 @@
from struct import iter_unpack
FORMAT = 'i12s2sf' # <1>
def text(field: bytes) -> str: # <2>
octets = field.split(b'\0', 1)[0] # <3>
return octets.decode('cp437') # <4>
with open('metro_areas.bin', 'rb') as fp: # <5>
data = fp.read()
for fields in iter_unpack(FORMAT, data): # <6>
year, name, country, pop = fields
place = text(name) + ', ' + text(country) # <7>
print(f'{year}\t{place}\t{pop:,.0f}')

View File

@@ -0,0 +1,46 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LEN 3
struct MetroArea {
int year;
char name[12];
char country[2];
float population;
};
int main(int argc, char* argv[]) {
struct MetroArea metro[LEN];
int rank;
metro[0].year = 2018;
strcpy(metro[0].name, "Tokyo");
metro[0].country[0] = 'J';
metro[0].country[1] = 'P';
metro[0].population = 43868229.0;
metro[1].year = 2015;
strcpy(metro[1].name, "Shanghai");
metro[1].country[0] = 'C';
metro[1].country[1] = 'N';
metro[1].population = 38700000.0;
metro[2].year = 2015;
strcpy(metro[2].name, "Jakarta");
metro[2].country[0] = 'I';
metro[2].country[1] = 'D';
metro[2].population = 31689592.0;
FILE* data;
if ( (data = fopen("metro_areas.bin", "wb")) == NULL ) {
printf("Error opening file\n");
return 1;
}
fwrite(metro, sizeof(struct MetroArea), LEN, data);
fclose(data);
return 0;
}