Centriraj tekst
Napisati program koji svaku liniju zadatog fajla ispisuje centriranu u okviru zadate širine, dodajući samo vodeće razmake.
Ulaz
Program se pokreće komandnom linijom oblika
./center <širina> <putanja_do_fajla>
gde <širina> predstavlja ciljnu širinu ispisa u znakovima, a <putanja_do_fajla> putanju do tekstualnog fajla koji sadrži linije teksta koje treba centrirati.
Izlaz
Na standardni izlaz ispisuju se centrirane linije u istom redosledu kao u ulaznom fajlu, svaka praćena novim redom.
Primer
moon_river.txt
Moon river, wider than a mile
I'm crossing you in style some day
Oh, dream maker, you heart breaker
Wherever you're going, I'm going your way
Two drifters, off to see the world
There's such a lot of world to see
We're after the same rainbow's end, waiting, round the bend
My Huckleberry Friend, Moon River, and me
Moon river, wider than a mile
I'm crossing you in style some day
Oh, dream maker, you heart breaker
Wherever you're going, I'm going your way
Two drifters, off to see the world
There's such a lot of world to see
We're after that same rainbow's end, waiting, round the bend
My Huckleberry Friend, Moon River, and me
command line
./center 80 moon_river.txt
stdout
Moon river, wider than a mile
I'm crossing you in style some day
Oh, dream maker, you heart breaker
Wherever you're going, I'm going your way
Two drifters, off to see the world
There's such a lot of world to see
We're after the same rainbow's end, waiting, round the bend
My Huckleberry Friend, Moon River, and me
Moon river, wider than a mile
I'm crossing you in style some day
Oh, dream maker, you heart breaker
Wherever you're going, I'm going your way
Two drifters, off to see the world
There's such a lot of world to see
We're after that same rainbow's end, waiting, round the bend
My Huckleberry Friend, Moon River, and me
Rešenje
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Error: Invalid number of arguments.\n");
exit(EXIT_FAILURE);
}
int width = atoi(argv[1]);
FILE *file = fopen(argv[2], "r");
if (file == NULL) {
fprintf(stderr, "Error: Could not open file %s\n", argv[2]);
exit(EXIT_FAILURE);
}
char line[1024];
while (fgets(line, sizeof (line), file) != NULL) {
int len = strlen(line);
if (line[len - 1] == '\n') {
len--;
line[len] = '\0';
}
int padding = (width - len) / 2;
if (padding < 0) {
padding = 0;
}
for (int i = 0; i < padding; i++) {
putchar(' ');
}
printf("%s\n", line);
}
fclose(file);
exit(EXIT_SUCCESS);
}