DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Dirty Replace Implement In C

03.29.2007
| 3230 views |
  • submit to reddit
        // description of your code here

while (feof (fp) == 0)
{	
	memset (file_buf, 0, file_size * sizeof (char));
	memset (line_buf, 0, sizeof (line_buf));

	if (fgets (line_buf, sizeof (line_buf), fp) == NULL && ferror (fp))
	{
		perror (file_path);
		fclose (fp);
		free (file_buf);
		return;
	}

	line_len = strlen (line_buf);

	if ((begin = (*(opt->str_str))(line_buf, opt->word)))
	{
		total_matches++;
		/* Example :{{{
			line_buf = '1234567890',  word = '5', replacement = '6'

			begin = address_of(5)
					address_of(5) - address_of(1) - line_len = -6
			
			fp now => '1234567890_' , at addressof(_)
			fseek (fp, -6)  => address_of (5)

			begin_offset = address_of (5);
			end_offset = begin_offset + strlen(repl) - 1 = address_of (5)
			
			so we should seek to end_offset + 1 to fread the rest.
			
			after reading.

			we fseek to the begin_offset, then write replacement, and write back the rest.

			finally we should seek to end_offset + 1 to read a new line

			}}} */
		if (fseek (fp, begin - line_buf - line_len, SEEK_CUR) < 0)
		{
			perror (file_path);
			fclose (fp);
			free (file_buf);
			return;
		}

		word_begin = ftell (fp);
		word_end = word_begin + (long) (strlen (opt->replacement) - 1);

		fseek (fp, word_end + 1, SEEK_SET);

		n = fread (file_buf, sizeof (char), file_size, fp);	// read until eof;

		fseek (fp, word_begin, SEEK_SET);
		
		fwrite (opt->replacement, sizeof (char), strlen (opt->replacement), fp);
		fwrite (file_buf, sizeof (char), n, fp);

		fseek (fp, word_end + 1, SEEK_SET);
	}

}