Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- const int writingIterations = 3;
- const int charsToWrite = 5;
- void writeDataInFile();
- void readDataFromFile();
- void printArr(int *arr,int n);
- int main() {
- writeDataInFile();
- readDataFromFile();
- return 0;
- }
- void writeDataInFile() {
- FILE *fp;
- int n =writingIterations;
- int num = 1;
- char letters[charsToWrite];
- for(int i = 0; i < charsToWrite; i++) {
- letters[i] = 'a' + i;
- }
- if((fp = fopen("nums.txt","wb")) == NULL) {
- printf("Error trying to find file.");
- exit(1);
- }
- //write one int and four chars
- for(int i = 0; i < n; i++) {
- if(fwrite(&num,sizeof(int),1,fp) != 1) {
- printf("Error trying to write num.");
- exit(1);
- }
- num++;
- for(int j = 0; j < 5; j++) {
- if(fwrite(&letters[j],sizeof(char),1,fp) != 1) {
- printf("Error trying to write char.");
- exit(1);
- }
- }
- }
- if(fclose(fp) == EOF) {
- printf("Error trying to close file ");
- exit(1);
- }
- }
- void readDataFromFile() {
- FILE *fp;
- int n,*arr,num,i,j;
- char letter;
- n = 10;
- if((arr = (int *)malloc(n*sizeof(int))) == NULL) {
- perror("Error allocatting memory");
- exit(1);
- }
- if((fp = fopen("nums.txt","rb")) == NULL) {
- printf("Error trying to find file.");
- exit(1);
- }
- i = 0;
- while(fread(&num,sizeof(int),1,fp) == 1) {
- arr[i++] = num;
- if(i == n) {
- n +=5;
- if((arr = (int *)realloc(arr,n * sizeof(int))) ==NULL) {
- perror("Problem with reallocating memory");
- exit(1);
- }
- }
- for(j = 0; j < 5; j++) {
- if(fread(&letter,sizeof(char),1,fp) != 1) {
- printf("Error trying to read char.");
- exit(1);
- }
- arr[i++] = (int)(letter);
- if(i == n) {
- n +=5;
- if((arr = (int *)realloc(arr,n * sizeof(int))) ==NULL) {
- perror("Problem with reallocating memory");
- exit(1);
- }
- }
- }
- }
- printArr(arr,n);
- free(arr);
- if(fclose(fp) == EOF) {
- printf("Error trying to close file ");
- exit(1);
- }
- }
- void printArr(int *arr,int n) {
- int i,j,k;
- for(i = 0,j = 0; i < writingIterations; i++) {
- printf("%d ",arr[j++]);
- for(int k = 0; k < charsToWrite; k++) {
- printf("%c ",arr[j++]);
- }
- printf("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement