danieljon.es

index posts opinions likes dislikes interesting cgit

Posts

My posts about programming and things.
Date format is DD/(M)M/YYYY because I'm sane.

string replacement in files

14/10/2018

I'm slowly rewriting my website generator in C and for it I required an easy way to write an input file to an output file replacing every instance of something with another string. So I made this convenience function that might be useful elsewhere one day.

int replaceinfile(char *originalfile, char *destinationfile, char *placeholder,
								char *replacement);
// 0 = failure, 1 = success

replaceinfile("input.txt", "output.txt", "%PLACEHOLDER%", "replacement string");
input.txt
Normal text file

%PLACEHOLDER%
%PLACEHOLDER%
%PLACEHOLDER%

With lines and whatever, %PLACEHOLDER%

123%PLACEHOLDER%123	
ok %PLACEHOLDER% ok
output.txt
Normal text file

replacement string
replacement string
replacement string

With lines and whatever, replacement string

123replacement string123	
ok replacement string ok
The source is available in my git repository.

page generated 2018-11-20 20:26:21 using sitegenerator