- zlib is a software library used for data compression.
- The zlib library provides Deflate compression and decompression code for use by zip, gzip, png (which uses the zlib wrapper on deflate data).
- gzread decompresses as you read it.
Program:
/* File based Database using Gunzip
* Check : http://velrajcoding.blogspot.in
*/
#include <stdio.h>
#include <zlib.h> // For gunzip
enum {
TAG_VER = 1,
TAG_DATA,
};
#define FILE_PATH_TMP "file_gz_db.gz.tmp"
#define FILE_PATH "file_gz_db.gz"
#define VERSION_1 1
#define STU_ID 100
#define STU_NAME "Velraj"
#define STU_TOTAL 500
void save_db()
{
char buf[256] = {0};
int len = 0;
gzFile gz_file = NULL;
if (!(gz_file = gzopen(FILE_PATH_TMP, "wb"))) {
printf("Failed gzopen !");
return;
}
len = snprintf(buf, sizeof(buf), "%d\a%d\n", TAG_VER, VERSION_1);
if (len != gzwrite(gz_file, buf, len)) {
printf("Failed to writing db header!");
goto end;
}
len = snprintf(buf, sizeof(buf), "%d\a%d\a%s\a%d\n", TAG_DATA,
STU_ID, STU_NAME, STU_TOTAL);
if (len != gzwrite(gz_file, buf, len)) {
printf("Failed to writing db header!");
goto end;
}
rename(FILE_PATH_TMP, FILE_PATH);
end:
gzclose(gz_file);
return;
}
void read_db()
{
gzFile gz_file = NULL;
char buf[256] = {0}, str_tag[16] = {0}, str_stu_id[12] = {0}, str_name[64] = {0}, str_total[12] = {0};
int tag = 0, version = 0, ret = 0;
if (!(gz_file = gzopen(FILE_PATH, "rb"))) {
printf("gzopen is failed to open the file");
return;
}
if (gzgets(gz_file, buf, sizeof(buf)) == NULL) {
printf("File is doesn't have any content");
goto end;
}
sscanf(buf, "%d\a%d", &tag, &version);
if ((tag != TAG_VER) || (version != VERSION_1)) {
printf("Failed tag or version");
goto end;
}
while (gzgets(gz_file, buf, sizeof(buf))) {
ret = sscanf(buf, "%d", &tag);
if (tag != TAG_DATA) {
continue;
}
ret = sscanf(buf, "%*[^\a]\a%[^\a]\a%[^\a]\a%[^\n]", str_stu_id, str_name, str_total);
if (ret != 3) {
printf("Failed to read student details ret:%d", ret);
continue;
}
printf("Read the data : ID:%s, Name:%s, Total:%s \n", str_stu_id, str_name, str_total);
}
end:
gzclose(gz_file);
return;
}
int main()
{
save_db();
read_db();
return 0;
}
Output:
:~/velrajk/sample$ gcc file_list_of_data.c -lz:~/velrajk/sample$ ls -l file_gz_db.gz
ls: cannot access file_gz_db.gz: No such file or directory
:~/velrajk/sample$ ./a.out
Read the data : ID:100, Name:Velraj, Total:500
:~/velrajk/sample$ ls -l file_gz_db.gz
-rw-rw-r-- 1 labuser labuser 41 Jul 22 14:44 file_gz_db.gz
:~/velrajk/sample$ gunzip file_gz_db.gz
:~/velrajk/sample$ cat file_gz_db
11
2100Velraj500
:~/velrajk/sample$
No comments:
Post a Comment