I'm creating this program that is going to:
1. Read a file
2. Find occurances of a substring within the string read in
3. Replace the occurances of this substring with another string
4. Write to new file
I have 1 and 4 down lol. Now I'm pretty new to C...though I have done C++. It's fairly different and I was hoping you guys can shed some light onto some functions I can use for finding and replacing the substring.Code:#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 512 #define _GNU_SOURCE int main(int argc, char *argv[]) { FILE *file, *file2; char line[MAX], *subLocation; if (argc != 4) { printf("You must enter: ./replace old-string new-string file-name\n"); exit(1); } file = fopen(argv[3], "r"); file2 = fopen("temp", "w"); while (fgets(line,sizeof(line),file) != NULL) { /* Search for string 1 in string buffer */ if (subLocation == NULL) { subLocation = strstr(line, argv[1]); /* position = subLocation-line */ /* Write the line */ fputs(line, file2); printf(line); /*Show me the line */ } /* Close everything */ fclose (file); fclose (file2); return 0; }
I've so far got strstr which will find the first occurance of the string (and i can loop to see if there is more than one). But I'm not sure what I should use to replace it. Any help would be greatly appreciated.
Thanks,
Dan



LinkBack URL
About LinkBacks
.


