#include #include #include const size_t BUFFER_SIZE = 1024; bool sar_in_line(const char* line, FILE* target, const char* search_text, const char* replacement_text) { // Move in the original line char by char trying to find search_text from that char for ( ; *line; ++line) { const char *s = search_text, *l = line; for ( ; *s && tolower(*s) == tolower(*l); ++s, ++l ) ; // If all chars of search_text were found in current position of line // write replacement_text to the target file and ignore those search_text characteres if ( *s == '\0' ) { if ( fputs(replacement_text, target) == EOF ) return false; line = l - 1; // should be line = l, but ++line in for will move it one more char } else { // No search_text is found from current position of line, write this char to target // file and try with next char of lines if ( fputc(*line, target) == EOF ) return false; } } return true; } bool sar_in_open_file(FILE* source, FILE* target, const char* search_text, const char* replacement_text) { // Read one line a time in source file, and write it with replacements to target file char buffer[BUFFER_SIZE]; while ( fgets(buffer, BUFFER_SIZE, source) ) if ( ! sar_in_line(buffer, target, search_text, replacement_text) ) return false; return true; } bool sar_in_file(const char* filename, const char* search_text, const char* replacement_text) { FILE* source = fopen(filename, "r"); if ( ! source ) { fprintf(stderr, "sar: could not open %s\n", filename); return false; } // Concatenate ".tmp" to source filename char target_filename[ strlen(filename) + strlen(".tmp") + 1 ]; strcpy(target_filename, filename); strcat(target_filename, ".tmp"); FILE* target = fopen(target_filename, "w"); if ( ! target ) { fprintf(stderr, "sar: could not create %s\n", target_filename); fclose(source); return false; } bool result = sar_in_open_file(source, target, search_text, replacement_text); fclose(target); fclose(source); // Replace original file for temporary file on success, remove temporary on error if ( result ) { remove(filename); rename(target_filename, filename); } else { fprintf(stderr, "sar: error writing to %s\n", target_filename); remove(target_filename); } return result; } int main(int argc, char* argv[]) { // Assumes: "sar -i -W search-text -r replacement-text file1.txt file2.txt ..." // position: 0 1 2 3 4 5 6 7 8... for ( int i = 6; i < argc; ++i ) sar_in_file( argv[i], argv[3], argv[5] ); return 0; }