Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. const int writingIterations = 3;
  5. const int charsToWrite = 5;
  6.  
  7. void writeDataInFile();
  8. void readDataFromFile();
  9. void printArr(int *arr,int n);
  10.  
  11. int main() {
  12. writeDataInFile();
  13. readDataFromFile();
  14. return 0;
  15. }
  16.  
  17. void writeDataInFile() {
  18. FILE *fp;
  19. int n =writingIterations;
  20. int num = 1;
  21. char letters[charsToWrite];
  22.  
  23. for(int i = 0; i < charsToWrite; i++) {
  24. letters[i] = 'a' + i;
  25. }
  26.  
  27. if((fp = fopen("nums.txt","wb")) == NULL) {
  28. printf("Error trying to find file.");
  29. exit(1);
  30. }
  31.  
  32. //write one int and four chars
  33. for(int i = 0; i < n; i++) {
  34. if(fwrite(&num,sizeof(int),1,fp) != 1) {
  35. printf("Error trying to write num.");
  36. exit(1);
  37. }
  38.  
  39. num++;
  40.  
  41. for(int j = 0; j < 5; j++) {
  42. if(fwrite(&letters[j],sizeof(char),1,fp) != 1) {
  43. printf("Error trying to write char.");
  44. exit(1);
  45. }
  46. }
  47. }
  48.  
  49. if(fclose(fp) == EOF) {
  50. printf("Error trying to close file ");
  51. exit(1);
  52. }
  53. }
  54.  
  55. void readDataFromFile() {
  56. FILE *fp;
  57. int n,*arr,num,i,j;
  58. char letter;
  59.  
  60. n = 10;
  61.  
  62. if((arr = (int *)malloc(n*sizeof(int))) == NULL) {
  63. perror("Error allocatting memory");
  64. exit(1);
  65. }
  66.  
  67. if((fp = fopen("nums.txt","rb")) == NULL) {
  68. printf("Error trying to find file.");
  69. exit(1);
  70. }
  71.  
  72. i = 0;
  73. while(fread(&num,sizeof(int),1,fp) == 1) {
  74. arr[i++] = num;
  75. if(i == n) {
  76. n +=5;
  77. if((arr = (int *)realloc(arr,n * sizeof(int))) ==NULL) {
  78. perror("Problem with reallocating memory");
  79. exit(1);
  80. }
  81. }
  82.  
  83. for(j = 0; j < 5; j++) {
  84. if(fread(&letter,sizeof(char),1,fp) != 1) {
  85. printf("Error trying to read char.");
  86. exit(1);
  87. }
  88. arr[i++] = (int)(letter);
  89. if(i == n) {
  90. n +=5;
  91. if((arr = (int *)realloc(arr,n * sizeof(int))) ==NULL) {
  92. perror("Problem with reallocating memory");
  93. exit(1);
  94. }
  95. }
  96. }
  97. }
  98.  
  99. printArr(arr,n);
  100.  
  101. free(arr);
  102. if(fclose(fp) == EOF) {
  103. printf("Error trying to close file ");
  104. exit(1);
  105. }
  106. }
  107.  
  108. void printArr(int *arr,int n) {
  109. int i,j,k;
  110.  
  111. for(i = 0,j = 0; i < writingIterations; i++) {
  112. printf("%d ",arr[j++]);
  113. for(int k = 0; k < charsToWrite; k++) {
  114. printf("%c ",arr[j++]);
  115. }
  116.  
  117. printf("\n");
  118. }
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement