Создать файл f, компонентами которого являются 10 целочисленных массивов - C (СИ)
Формулировка задачи:
Решение задачи: «Создать файл f, компонентами которого являются 10 целочисленных массивов»
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define NUM_OF_ARRAYS 10
- #define SIZE_OF_ARRAY 12
- int* createArray(size_t sz);
- void fillArray(int* a, size_t sz);
- int* readArray( FILE* file, size_t sz);
- void writeArray(FILE* file, int* a, size_t sz);
- int max(int *a, size_t sz);
- void replaceMax(int *a, size_t sz);
- void printArray(int* a, size_t sz);
- void check_file(FILE* file);
- void check_array(int* a);
- void createFile(FILE* file, const char *fn);
- void modifyFile(FILE *f);
- int main(){
- FILE *f=NULL;
- srand(time(0));
- createFile(f, "data.dat");
- puts("----------------------------------");
- modifyFile(f);
- return 0;
- }
- void modifyFile(FILE *file){
- size_t i=0, n=SIZE_OF_ARRAY;
- long rpos, wpos;
- file=fopen("data.dat", "r+b");
- check_file(file);
- for(i=0; i<NUM_OF_ARRAYS; ++i){
- wpos=ftell(file);
- int *b=readArray(file, n);
- check_array(b);
- rpos=ftell(file);
- replaceMax(b,n);
- fseek(file, wpos, SEEK_SET);
- writeArray(file, b, n);
- fseek(file, rpos, SEEK_SET);
- free(b);
- }
- rewind(file);
- for(i=0; i<NUM_OF_ARRAYS; ++i){
- int *b=readArray(file, n);
- check_array(b);
- printArray(b,n);
- free(b);
- }
- }
- void createFile(FILE* file, const char *fn){
- size_t i=0;
- size_t n=SIZE_OF_ARRAY;
- file=fopen(fn, "wb");
- check_file(file);
- for(i=0; i<NUM_OF_ARRAYS; ++i){
- int *a=createArray(n);
- printArray(a,n);
- writeArray(file, a, n);
- free(a);
- }
- fclose(file);
- }
- void check_array(int* a){
- if(!a){
- puts("No memory.");
- exit(EXIT_FAILURE);
- }
- }
- void check_file(FILE* file){
- if(!file){
- perror ("file not found");
- exit(EXIT_FAILURE);
- }
- }
- void printArray(int *a, size_t sz){
- size_t i=0;
- for(i=0; i<sz;++i){
- printf("%6d", *(a+i));
- }
- puts("");
- }
- int* createArray(size_t sz){
- int *a=(int*)malloc(sz*sizeof(int));
- check_array(a);
- fillArray(a, sz);
- return a;
- }
- void fillArray(int *a, size_t sz){
- size_t i=0;
- for(i=0; i<sz;++i){
- a[i]=rand()%100+1; // 0..99
- }
- }
- int* readArray( FILE *file, size_t sz){
- int *arr=(int*)malloc(sz*sizeof(int));
- check_array(arr);
- fread(arr, sizeof(int), sz, file);
- return arr;
- }
- void writeArray(FILE *file, int* a, size_t sz){
- fwrite(a, sizeof(int), sz, file);
- }
- int max(int *a, size_t sz){
- size_t i=0;
- int max=a[i];
- for (i=1; i<sz; ++i){
- if(max<a[i])
- max=a[i];
- }
- return max;
- }
Объяснение кода листинга программы
Код представляет собой программу для работы с файлом data.dat
, который содержит 10 массивов по 12 целых чисел. В основной функции создается файл data.dat
, если он не существует, и открывается для чтения и записи. Затем в цикле создаются 10 массивов, заполняются случайными числами от 1 до 100, записываются в файл, затем считываются обратно, проверяются на корректность заполнения, выводится на экран и освобождается память.
Далее в функции modifyFile
в цикле сначала считываются все массивы из файла, затем заменяется максимальное значение в каждом массиве на следующее по порядку, после чего обновленные массивы записываются обратно в файл.
В конце программы выводится сообщение о успешном выполнении.
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д