Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. replace words in a file

replace words in a file

Scheduled Pinned Locked Moved C / C++ / MFC
database
7 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U Offline
    U Offline
    User 12925011
    wrote on last edited by
    #1

    The task is to replace - looks for all occurrences of string from and replaces it with string to. It is possible to specify one or more files on which to perform the replace operation(s) in a single replace command. and this is my code: void replace(char* OldWord, char* NewWord) { char *result = NULL; char buff[1000]; char c; char line[1000]; FILE * f = fopen ("file1.txt", "r+"); int count=0; while (fgets(buff, sizeof(buff), f)) { result = replaceWord(buff, OldWord, NewWord); // } // //free(result); } char *replaceWord(const char *s, const char *oldW,const char *newW) { char *result; int i, cnt = 0; int newWlen = strlen(newW); int oldWlen = strlen(oldW); static int k=0; k++; char newline[1000]; FILE * fp; // printf("%s\n",oldW); //printf("%s\n",newW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1); i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; fp = fopen ("file1.txt", "w"); rewind(fp); fseek(fp,i-newWlen,SEEK_SET); fprintf(fp,"%s\n",result); } else { result[i++] = *s++; } } result[i] = '\0'; fp = fopen ("file1.txt", "w"); fprintf(fp,"%s\n",result); // printf("%d\n",k); return result; } the replace function does not give the desired output The command line looks like: ./a.out replace old_word new_word files.txt must replace old_word with the new_word in all files.

    V K D S 4 Replies Last reply
    0
    • U User 12925011

      The task is to replace - looks for all occurrences of string from and replaces it with string to. It is possible to specify one or more files on which to perform the replace operation(s) in a single replace command. and this is my code: void replace(char* OldWord, char* NewWord) { char *result = NULL; char buff[1000]; char c; char line[1000]; FILE * f = fopen ("file1.txt", "r+"); int count=0; while (fgets(buff, sizeof(buff), f)) { result = replaceWord(buff, OldWord, NewWord); // } // //free(result); } char *replaceWord(const char *s, const char *oldW,const char *newW) { char *result; int i, cnt = 0; int newWlen = strlen(newW); int oldWlen = strlen(oldW); static int k=0; k++; char newline[1000]; FILE * fp; // printf("%s\n",oldW); //printf("%s\n",newW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1); i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; fp = fopen ("file1.txt", "w"); rewind(fp); fseek(fp,i-newWlen,SEEK_SET); fprintf(fp,"%s\n",result); } else { result[i++] = *s++; } } result[i] = '\0'; fp = fopen ("file1.txt", "w"); fprintf(fp,"%s\n",result); // printf("%d\n",k); return result; } the replace function does not give the desired output The command line looks like: ./a.out replace old_word new_word files.txt must replace old_word with the new_word in all files.

      V Offline
      V Offline
      Victor Nijegorodov
      wrote on last edited by
      #2

      Member 12957547 wrote:

      It is possible to specify one or more files on which to perform the replace operation(s) in a single replace command.

      Why "in a single replace command"? Why not just open your files in the loop and perform the replacement in each file? :confused:

      U 1 Reply Last reply
      0
      • V Victor Nijegorodov

        Member 12957547 wrote:

        It is possible to specify one or more files on which to perform the replace operation(s) in a single replace command.

        Why "in a single replace command"? Why not just open your files in the loop and perform the replacement in each file? :confused:

        U Offline
        U Offline
        User 12925011
        wrote on last edited by
        #3

        because I do not know how many items get from the CLI

        K 1 Reply Last reply
        0
        • U User 12925011

          The task is to replace - looks for all occurrences of string from and replaces it with string to. It is possible to specify one or more files on which to perform the replace operation(s) in a single replace command. and this is my code: void replace(char* OldWord, char* NewWord) { char *result = NULL; char buff[1000]; char c; char line[1000]; FILE * f = fopen ("file1.txt", "r+"); int count=0; while (fgets(buff, sizeof(buff), f)) { result = replaceWord(buff, OldWord, NewWord); // } // //free(result); } char *replaceWord(const char *s, const char *oldW,const char *newW) { char *result; int i, cnt = 0; int newWlen = strlen(newW); int oldWlen = strlen(oldW); static int k=0; k++; char newline[1000]; FILE * fp; // printf("%s\n",oldW); //printf("%s\n",newW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1); i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; fp = fopen ("file1.txt", "w"); rewind(fp); fseek(fp,i-newWlen,SEEK_SET); fprintf(fp,"%s\n",result); } else { result[i++] = *s++; } } result[i] = '\0'; fp = fopen ("file1.txt", "w"); fprintf(fp,"%s\n",result); // printf("%d\n",k); return result; } the replace function does not give the desired output The command line looks like: ./a.out replace old_word new_word files.txt must replace old_word with the new_word in all files.

          K Offline
          K Offline
          k5054
          wrote on last edited by
          #4

          Haven't tried to run your code, but I do notice a couple things: 1: you call fopen() several times, but there's no corresponding fclose(). If you had a large file (say the text of the bible), and wanted to replace, "god" with "jimmy", you would probably run out of file handles before completing the task. 2: you continually call fopen on the same file. fopen("file1.txt", "w") truncates the file, so some future read may return EOF unexpectedly. [NB not necessarily the next read, as the call to fgets might fill an input buffer, which following calls use, rather than continually reading from the file] My suggestion would be to open a temporary file and write your output there, then copy or replace the input file with the temp file. tmpfile() might be useful, here. 3: fgets() reads up to size-1 bytes from the input stream. What happens if you have very long lines (over 999 chars, in your case), and the word you want occupies chars 996-1003? You'll get the first 3 chars in one read and the remaining 4 in the next, missing an occurrence. Might I suggest you look at getline(). 4: do you need to concern yourself with word case? Do you need to replace "babble" with "brook", "Babble" with "Brook" and "BABBLE" with "BROOK"?

          1 Reply Last reply
          0
          • U User 12925011

            because I do not know how many items get from the CLI

            K Offline
            K Offline
            k5054
            wrote on last edited by
            #5

            Member 12957547 wrote:

            because I do not know how many items get from the CLI

            Yes, you do, or at least main() does.

            int main(int argc, char **argv)

            argc is the number of arguments passed to main, and argv is an array of strings containing the command line arguments. Remeber that argv[0] is the program name, so argc is always > 0. The following will print all the command line arguments

            #include

            int main(int argc, char **argv)
            {
            for(int i = 0; i < argc; ++i)
            printf("argv[%d] = \"%s\"\n", i, argv[i];
            return0;
            }

            1 Reply Last reply
            0
            • U User 12925011

              The task is to replace - looks for all occurrences of string from and replaces it with string to. It is possible to specify one or more files on which to perform the replace operation(s) in a single replace command. and this is my code: void replace(char* OldWord, char* NewWord) { char *result = NULL; char buff[1000]; char c; char line[1000]; FILE * f = fopen ("file1.txt", "r+"); int count=0; while (fgets(buff, sizeof(buff), f)) { result = replaceWord(buff, OldWord, NewWord); // } // //free(result); } char *replaceWord(const char *s, const char *oldW,const char *newW) { char *result; int i, cnt = 0; int newWlen = strlen(newW); int oldWlen = strlen(oldW); static int k=0; k++; char newline[1000]; FILE * fp; // printf("%s\n",oldW); //printf("%s\n",newW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1); i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; fp = fopen ("file1.txt", "w"); rewind(fp); fseek(fp,i-newWlen,SEEK_SET); fprintf(fp,"%s\n",result); } else { result[i++] = *s++; } } result[i] = '\0'; fp = fopen ("file1.txt", "w"); fprintf(fp,"%s\n",result); // printf("%d\n",k); return result; } the replace function does not give the desired output The command line looks like: ./a.out replace old_word new_word files.txt must replace old_word with the new_word in all files.

              D Offline
              D Offline
              David Crow
              wrote on last edited by
              #6

              Member 12957547 wrote:

              the replace function does not give the desired output

              If that is the case, I'd take a step back and get it working before worrying about files. Just send the function a string of characters, and the find/replace terms. After that, then rope the file contents back in.

              "One man's wage rise is another man's price increase." - Harold Wilson

              "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

              "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

              1 Reply Last reply
              0
              • U User 12925011

                The task is to replace - looks for all occurrences of string from and replaces it with string to. It is possible to specify one or more files on which to perform the replace operation(s) in a single replace command. and this is my code: void replace(char* OldWord, char* NewWord) { char *result = NULL; char buff[1000]; char c; char line[1000]; FILE * f = fopen ("file1.txt", "r+"); int count=0; while (fgets(buff, sizeof(buff), f)) { result = replaceWord(buff, OldWord, NewWord); // } // //free(result); } char *replaceWord(const char *s, const char *oldW,const char *newW) { char *result; int i, cnt = 0; int newWlen = strlen(newW); int oldWlen = strlen(oldW); static int k=0; k++; char newline[1000]; FILE * fp; // printf("%s\n",oldW); //printf("%s\n",newW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1); i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; fp = fopen ("file1.txt", "w"); rewind(fp); fseek(fp,i-newWlen,SEEK_SET); fprintf(fp,"%s\n",result); } else { result[i++] = *s++; } } result[i] = '\0'; fp = fopen ("file1.txt", "w"); fprintf(fp,"%s\n",result); // printf("%d\n",k); return result; } the replace function does not give the desired output The command line looks like: ./a.out replace old_word new_word files.txt must replace old_word with the new_word in all files.

                S Offline
                S Offline
                Stefan_Lang
                wrote on last edited by
                #7

                A couple of things I've noticed: 1. You are always using 'file1.txt' in your code, not the filename(s) passed as argument 2. As has been pointed out, lines can be longer than 1000 chars. 3. You never close the file you've opened. That will cause changes in one file buffer to overwrite previous changes once the files are closed (or at the end of the program). 4. You only check for one occurence of a word per line. What if there are multiple occurrences? Suggestions: - As already pointed out, start with your replace functions and make sure they work as intended, before dealing with files! - Make sure you always close the files you've opened - Write the modified text into another, temporary file. Later erase the original file, and rename the temporary one. That way you can just keep on reading/writing without needing to close/open the file over and over again.

                GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups