المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : How to re-use the replace() function to replace different strings in the same file ?



C++ Programming
02-13-2012, 03:21 PM
Hi,
I have a replace function which replaces all the occurences of the string into another file. But when I use the replace function multiple times... it replaces the string which was passed in the last call only and all the previous replacement does not happen.
Below is the code
replace(char text2find[80],char text2repl[80]) { char fileOrig[32] = "OrigFile.txt"; char fileRepl[32] = "ReplacedFile.txt"; char buffer[MAX_LEN_SINGLE_LINE+2]; char *buff_ptr, *find_ptr, *tok; FILE *fp1, *fp2; size_t find_len = strlen(text2find); fp1 = fopen(fileOrig,"r"); fp2 = fopen(fileRepl,"w+"); while(fgets(buffer,MAX_LEN_SINGLE_LINE+2,fp1)) { buff_ptr = buffer; tok = strtok(buff_ptr,"*");//ignores the string occurence after * if(tok != NULL) { while ((find_ptr = strstr(buff_ptr,text2find))) { while(buff_ptr < find_ptr) fputc((int)*buff_ptr++,fp2); fputs(text2repl,fp2); buff_ptr += find_len; } fputs(buff_ptr,fp2); } } rewind(fp1); rewind(fp2); fclose(fp2); fclose(fp1); }I wud actually wanto replace all the string in the same file, but am finding it tough and also reuse of the replace function multiple times wud be difficult. Hence went with two files...


Thanks,
Faez