Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. enum { MAXIMUM_SIZE = 4096 };
  10.  
  11. struct FileContent {
  12. ssize_t size;
  13. char *data;
  14. };
  15.  
  16. ssize_t inputAmount(int fd, char *buf) {
  17. ssize_t symbols = 0;
  18. while (symbols < MAXIMUM_SIZE) {
  19. ssize_t readPart = read(fd, buf + symbols, MAXIMUM_SIZE - symbols);
  20. if (readPart == -1) {
  21. return -1;
  22. } else if (readPart == 0){
  23. return symbols;
  24. }
  25. symbols += readPart;
  26. }
  27. return symbols;
  28. }
  29.  
  30. struct FileContent read_file(int fd) {
  31. ssize_t symbols = 0, readedSymbols = 0, memSize = 1;
  32. struct FileContent badExit = { -1, NULL };
  33. char *data = malloc(sizeof(*data));
  34. char buf[MAXIMUM_SIZE];
  35. if (!data) {
  36. return badExit;
  37. }
  38.  
  39. int reading = 1;
  40. while (reading) {
  41. ssize_t reading = inputAmount(fd, buf);
  42. if (reading == -1) {
  43. free(data);
  44. return badExit;
  45. }
  46. if (!reading) {
  47. break;
  48. }
  49.  
  50. while (readedSymbols + symbols >= memSize) {
  51. memSize *= 2;
  52. }
  53. char * copydata = realloc(data, memSize * sizeof(*copydata));
  54. if (!copydata) {
  55. free(data);
  56. return badExit;
  57. }
  58. data = copydata;
  59. memcpy(data + readedSymbols, buf, symbols);
  60. readedSymbols += symbols;
  61. }
  62.  
  63. data[readedSymbols] = 0;
  64. badExit.size = readedSymbols;
  65. badExit.data = data;
  66. return badExit;
  67. };
  68.  
  69. int main(int argc, char **argv) {
  70. int fd = open("in.txt", O_RDONLY);
  71. printf("%d\n", fd);
  72. struct FileContent kek = read_file(fd);
  73. printf("%d\n", kek.size);
  74. for (int i = 0; i < kek.size; ++i) {
  75. printf("%c", kek.data[i]);
  76. }
  77. printf("\n");
  78. free(kek.data);
  79. return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement