Hi there,
I've got this piece of code, but I'm having trouble getting it to write the changes into the file.
What I'm trying to do is:
At the moment it compiles fine (with a few warnings) but when I check the file it does not have the changes made to it.
User would input something like: ./a.out myfile.txt a b
(that is - take myfile.txt - replace all a's and replace with b's)
Any help would be greatly appreciated!
I've got this piece of code, but I'm having trouble getting it to write the changes into the file.
What I'm trying to do is:
- Read text file
- Find user specified character (eg. what to replace all the a's)
- Replace the character (eg. replace all a's with b's)
- Write to the same text file
Code:
#include <stdio.h> #include <string.h> #define MAX_LEN_SINGLE_LINE 1000 int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "Format should be: %s char to replace char replacing\n", argv[0]); return 1; } char buffer[MAX_LEN_SINGLE_LINE+2]; char *buff_ptr, *find_ptr, temp; FILE *fp1; size_t find_len = strlen(argv[2]); fp1 = fopen(argv[1],"r"); while(fgets(buffer,MAX_LEN_SINGLE_LINE+2,fp1)) { buff_ptr = buffer; while ((find_ptr = strstr(buff_ptr,argv[2]))) { while(buff_ptr < find_ptr) fputc((int)*buff_ptr++,fp1); fputs(argv[3],fp1); buff_ptr += find_len; } fputs(buff_ptr,fp1); } fclose(fp1); return 0; }
User would input something like: ./a.out myfile.txt a b
(that is - take myfile.txt - replace all a's and replace with b's)
Any help would be greatly appreciated!
Comment