emp-toolkit
file_io_channel.h
Go to the documentation of this file.
1 #ifndef FILE_IO_CHANNEL_H__
2 #define FILE_IO_CHANNEL_H__
3 
4 #include <iostream>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <arpa/inet.h>
10 #include <sys/types.h>
11 #include <netinet/in.h>
12 #include <sys/socket.h>
13 #include <string>
14 #include "io_channel.h"
15 using namespace std;
16 
21 class FileIO: public IOChannel<FileIO> { public:
22  uint64_t bytes_sent = 0;
23  int mysocket = -1;
24  FILE * stream = nullptr;
25  char * buffer = nullptr;
26  FileIO(const char * file, bool read) {
27  if (read)
28  stream = fopen(file, "rb+");
29  else
30  stream = fopen(file, "wb+");
31  buffer = new char[FILE_BUFFER_SIZE];
32  memset(buffer, 0, FILE_BUFFER_SIZE);
33  setvbuf(stream, buffer, _IOFBF, FILE_BUFFER_SIZE);
34  }
35 
37  fflush(stream);
38  fclose(stream);
39  delete[] buffer;
40  }
41 
42  void flush() {
43  fflush(stream);
44  }
45 
46  void reset() {
47  rewind(stream);
48  }
49  void send_data_impl(const void * data, int len) {
50  bytes_sent += len;
51  int sent = 0;
52  while(sent < len) {
53  int res = fwrite(sent+(char*)data, 1, len-sent, stream);
54  if (res >= 0)
55  sent+=res;
56  else
57  fprintf(stderr,"error: file_send_data %d\n", res);
58  }
59  }
60  void recv_data_impl(void * data, int len) {
61  int sent = 0;
62  while(sent < len) {
63  int res = fread(sent+(char*)data, 1, len-sent, stream);
64  if (res >= 0)
65  sent+=res;
66  else
67  fprintf(stderr,"error: file_recv_data %d\n", res);
68  }
69  }
70 };
72 #endif//FILE_IO_CHANNEL
void recv_data_impl(void *data, int len)
Definition: file_io_channel.h:60
void send_data_impl(const void *data, int len)
Definition: file_io_channel.h:49
void reset()
Definition: file_io_channel.h:46
#define FILE_BUFFER_SIZE
Definition: config.h:8
~FileIO()
Definition: file_io_channel.h:36
FileIO(const char *file, bool read)
Definition: file_io_channel.h:26
Definition: io_channel.h:12
void flush()
Definition: file_io_channel.h:42
Definition: file_io_channel.h:21