Zameni reč
Napisati program koji u zadatoj tekstualnoj datoteci pronalazi sve pojave tačno određene reči i zamenjuje ih novom rečju, pri čemu rezultat upisuje u drugi fajl.
Ulaz
Program se pokreće komandnom linijom oblika
./replace <ulazni_fajl> <izlazni_fajl> <stara_reč> <nova_reč>
Ulazni fajl se čita token po token (razdvajanje po belinama).
Izlaz
Svaki token identičan <stara_reč> zamenjuje se vrednošću <nova_reč>, svi ostali tokeni se upisuju neizmenjeni. Rezultat se upisuje u <izlazni_fajl>.
Primer
ulaz.txt
hello world
hello again
command line
./replace ulaz.txt izlaz.txt hello hi
izlaz.txt
hi world hi again
Primer
command line
./replace input.txt output.txt test exam
stderr
Error: Could not open file input.txt
Primer
command line
./replace input.txt
stderr
Error: Invalid number of arguments.
Rešenje
main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc != 5) {
fprintf(stderr, "Error: Invalid number of arguments.\n");
exit(EXIT_FAILURE);
}
FILE *file_in = fopen(argv[1], "r");
if (file_in == NULL) {
fprintf(stderr, "Error: Could not open file %s\n", argv[1]);
exit(EXIT_FAILURE);
}
FILE *file_out = fopen(argv[2], "w");
if (file_out == NULL) {
fprintf(stderr, "Error: Could not open file %s\n", argv[2]);
fclose(file_in);
exit(EXIT_FAILURE);
}
const char *old_word = argv[3];
const char *new_word = argv[4];
char word[1024];
while (fscanf(file_in, "%s", word) == 1) {
if (strcmp(word, old_word) == 0) {
fprintf(file_out, "%s ", new_word);
} else {
fprintf(file_out, "%s ", word);
}
}
fclose(file_out);
fclose(file_in);
exit(EXIT_SUCCESS);
}