This program will perform a find and replace on a single word in a file, with the condition that the new word must have the same length as the old one. It will also display the number of occurrences of the old word.
I'm not interested in anything type of feedback, anything would be appreciated, it's a school assignment and it'll be reviewed by my teacher.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_SIZE 24
void write_to_file(const char *s);
void replace_word(const char *s, const char *old_word, const char *new_word);
int main(void){
const char file_name[] = "text.txt";
int c;
char old_word[WORD_SIZE];
char new_word[WORD_SIZE];
puts("Enter 'w' to write to the file, 'r' to replace a word");
while((c = getchar()) != EOF){
switch(c){
case 'w':
getchar();
write_to_file(file_name);
break;
case 'r':
getchar();
puts("Enter the word you want to replace");
fgets(old_word, sizeof(old_word), stdin);
old_word[strlen(old_word) - 1] = '\0';
puts("Enter the new word");
fgets(new_word, sizeof(new_word), stdin);
new_word[strlen(new_word) - 1] = '\0';
if(strlen(old_word) != strlen(new_word)){
printf("Error: can't replace \"%s\" with \"%s\":\n\"%s\" the length is not the same", old_word, new_word, new_word);
break;
}
replace_word(file_name, old_word, new_word);
break;
default:
printf("Invalid command:%i\n", c);
break;
}
}
return 0;
}
void write_to_file(const char *s){
FILE *in_file;
if((in_file = fopen(s, "w")) == NULL){
perror(s);
exit(EXIT_FAILURE);
}
int c;
while((c = getchar()) != EOF){
fputc(c, in_file);
}
fclose(in_file);
}
unsigned long fsize(const char *s){
FILE *f;
if((f = fopen(s, "r")) == NULL){
perror(s);
exit(EXIT_FAILURE);
}
fseek(f, 0, SEEK_END);
unsigned long len = ftell(f);
fclose(f);
return len;
}
void replace_word(const char *s, const char *old_word, const char *new_word){
FILE *original_file;
FILE *copy;
if((original_file = fopen(s, "r")) == NULL){
perror(s);
exit(EXIT_FAILURE);
}
if((copy = fopen("copy.txt", "w")) == NULL){
perror("text");
exit(EXIT_FAILURE);
}
const int BUFFER_SIZE = fsize(s);
char *buffer = malloc(BUFFER_SIZE);
char *init_loc = buffer;
int word_len = strlen(old_word);
int word_frequency = 0;
while(fgets(buffer, BUFFER_SIZE, original_file)){
while((buffer = strstr(buffer, old_word))){
memcpy(buffer, new_word, word_len);
word_frequency++;
}
buffer = init_loc;
fprintf(copy, "%s", buffer);
}
printf("'%s' found %i times\n", old_word, word_frequency);
fclose(original_file);
fclose(copy);
if((original_file = fopen(s, "w")) == NULL){
perror(s);
exit(EXIT_FAILURE);
}
if((copy = fopen("copy.txt", "r")) == NULL){
perror("text");
exit(EXIT_FAILURE);
}
int c;
while((c = fgetc(copy)) != EOF){
fputc(c, original_file);
}
fclose(original_file);
fclose(copy);
free(buffer);
}
sed -e 's/<word1>/<word2>/g'
\$\endgroup\$