0

I am trying to write some short C code that will find the word "Applicat" and replace that entire line with something else, not just the word. For example, I have a test.txt file that says:

Name: test

Applicat: something

Date: today

My current code would find the word "Applicat," and replace it with "Applicat: ft_link," but the "something" is still there. How can I make it look like this:

Name: test

Applicat: ft_link

Date: today

?

Or is there an easier way to do this?

Thanks in advance!

Here is the main part of my code:

 char buffer[512]; while (fgets(buffer, sizeof(buffer), input) != NULL) { static const char text_to_find[] = "Applicat:"; static const char text_to_replace[] = "Applicat: ft_link"; char *pos = strstr(buffer, text_to_find); if (pos != NULL) { char *temp = calloc( strlen(buffer) - strlen(text_to_find) + strlen(text_to_replace) + 1, 1); memcpy(temp, buffer, pos - buffer); memcpy(temp + (pos - buffer), text_to_replace, strlen(text_to_replace)); memcpy(temp + (pos - buffer) + strlen(text_to_replace), pos + strlen(text_to_find), 1 + strlen(buffer) - ((pos - buffer) + strlen(text_to_find))); fputs(temp, output); free(temp); } 

1 Answer 1

1

Assuming that your output filename is not the same as your input filename

If you are replacing the whole line, then you can simply just write text_to_replace to the file with a newline character.

char buffer[512]; while (fgets(buffer, sizeof(buffer), input) != NULL) { static const char text_to_find[] = "Applicat:"; static const char text_to_replace[] = "Applicat: ft_link\n"; // Added newline char *pos = strstr(buffer, text_to_find); if (pos != NULL) { fputs(text_to_replace, output); } } 
Sign up to request clarification or add additional context in comments.

5 Comments

A good answer. The file should be read line by line though, what if "Applicat:" appears at file position 510?
From his code, he is reading the file line by line, unless his lines are longer that 512 characters(including newline). fgets() should read only a line unless as I said his lines are longer that the buffer size
That was quick and easy. Thank you very much sir @T.V.
One more question if you don't mind, what if now i want to change more than one line? I tried just copying another if statement with new "Name" char declared, but it ended up just duplicating a few lines. SHould i be doing them all in the same if statement? Thanks.
You question is somewhat vague, because the current code should replace all lines that contain Applicat:. Do you mean you want to replace all lines that contain Applicat: and Name?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.