HLPL/task1/task1.c

78 lines
1.8 KiB
C
Raw Normal View History

#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
typedef struct {
FILE *file;
long int size_of_file;
char *contents;
} TEXTFILE;
long int filesize(FILE *fp) {
long int size_of_file;
fseek(fp, 0, SEEK_END);
size_of_file = ftell(fp);
fseek(fp, 0, SEEK_SET);
return(size_of_file);
}
TEXTFILE* init_file(char* path) {
TEXTFILE *buf;
buf = malloc(sizeof(TEXTFILE));
if (buf == NULL) {
fprintf(stderr, "Error allocating structure");
return NULL;
}
buf -> file = fopen(path, "r");
if (buf -> file == NULL) {
fprintf(stderr, "Error opening file");
free(buf);
return NULL;
}
buf -> size_of_file = filesize(buf -> file);
buf -> contents = (char *)malloc(buf -> size_of_file);
if (buf -> contents == NULL) {
fprintf(stderr, "Error allocating contents array");
fclose(buf -> file);
free(buf);
return NULL;
}
fread(buf -> contents, sizeof(char), buf -> size_of_file, buf -> file);
return buf;
}
void close_file(TEXTFILE* file) {
free(file -> contents);
fclose(file -> file);
free(file);
}
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("Некорректные аргументы. Требуется файл для чтения и файл для записи.\n");
return 1;
} else {
TEXTFILE* input_file = init_file(argv[1]);
if (input_file == NULL) { return 1;}
char* pos;
pos = strstr(input_file -> contents, "777");
while (pos != NULL) {
*pos = 'M';
*(pos+1) = 'A';
*(pos+2) = 'I';
pos = strstr(pos, "777");
}
FILE* output_file = fopen(argv[2], "w");
if (output_file == NULL) {
fprintf(stderr, "Error opening output file");
} else {
fwrite(input_file -> contents, sizeof(char), input_file -> size_of_file, output_file);
fclose(output_file);
}
close_file(input_file);
return 0;
}
}