二进制文件读写

以二进制文件记录集群资源信息。

文件类:

 1 class BinaryFile
 2 {
 3 public:
 4     BinaryFile(const string& filepath) {
 5         file_buf_ = NULL;
 6         memset(file_path_, 0, 128);
 7         strncpy(file_path_, filepath.c_str(), 127);
 8     }
 9     ~BinaryFile() {
10         if (file_buf_ != NULL)
11             delete[] file_buf_;
12     }
13     void InitBuf(unsigned int size) {
14         buf_size_ = size;
15         file_buf_ = new char[size];
16         memset(file_buf_, 0, size);
17     }
18     
19 public:
20     int     buf_size_;
21     char*   file_buf_;
22     char    file_path_[128];
23 };

 

写文件:

 1 int WriteBinaryFile(const BinaryFile& bfile)
 2 {
 3     // need lock
 4     ofstream ofs(bfile.file_path_, ios_base::binary | ios_base::out | ios_base::trunc);
 5     
 6     if (!ofs.is_open()) {
 7         // need unlock
 8         printf("Failed to open file: %s, errno: %d\n", bfile.file_path_, errno);
 9         return -1;
10     }
11     
12     ofs.write((char*)&bfile.buf_size_, sizeof(int));
13     ofs.write(bfile.file_buf_, bfile.buf_size_);
14     
15     if (!ofs) {
16         // need unlock
17         printf("Write invalid file: %s, size=%d\n", bfile.file_path_, bfile.buf_size_);
18         return -1;
19     }
20     
21     ofs.close();
22     // need unlock
23     return bfile.buf_size_;
24 }

 

读文件:

 1 int ReadBinaryFile(BinaryFile& bfile)
 2 {
 3     // need lock
 4     ifstream ifs(bfile.file_path_, ios_base::in | ios_base::binary);
 5     
 6     if (!ifs.is_open()) {
 7         // need unlock
 8         printf("Failed to open file: %s, errno: %d\n", bfile.file_path_, errno);
 9         return -1;
10     }
11     
12     ifs.seekg (0, ifs.end);
13     int file_size = ifs.tellg();
14     ifs.seekg (0, ifs.beg);
15     int data_buf_size = 0;
16     ifs.read((char*)(&data_buf_size), sizeof(int));
17     
18     if (data_buf_size != file_size - sizeof(int)) {
19         // need unlock
20         printf("Read invalid file: file_size=%d, data_buf_size=%d\n", file_size, data_buf_size);
21         return -1;
22     }
23     
24     bfile.InitBuf(data_buf_size);
25     ifs.read(bfile.file_buf_, data_buf_size);
26     int read_size = ifs.gcount();
27     
28     if (!ifs) {
29         // need unlock
30         printf("Read invalid file: file_size=%d, read_size=%d\n", file_size, read_size);
31         return -1;
32     }
33     
34     ifs.close();
35     // need unlock
36     // printf("ReadBinaryFile: file_size=%d, read_size=%d\n", file_size, read_size);
37     return read_size;
38 }

 

posted @ 2017-09-20 00:03  lausaa  阅读(184)  评论(0)    收藏  举报