0

my task is to replace a string with another string in a file line. I am still in the beginning of my studies in C programming language and I am facing some problems. I should find the lines beginning with #define, get their values and delete them. Then wherever the constant name appears, it should be replaced with its value. I have already saved the define values from the file but I have some difficulties in replacing the constant names with their values. So far I have two arrays where I have saved the constant names and the values:

char constant_names[256];
char constant_values[256];

I will be so thankful if you can give me some ideas about the solution of the task.

4
  • 1
    Can we see the code? This might be a difficult exercises because 1) You can't replace text in a file without rewriting the whole file and 2) Trying to match an arbitrary number of define tags will not be trivial Commented Feb 28, 2019 at 20:47
  • You'll want to copy the original file, line by line, to a new file. When you come across what you want to change, change it and write it to the new file. Then copy the new file to the old file. Commented Feb 28, 2019 at 20:58
  • I would rewrite the file with another extension (you seem to be writing a preprocessor). chars are written one after another in memory, so you cannot do it in the same file. If you want, later, you can delete the old file, and save the new one with the same name. Commented Feb 28, 2019 at 20:59
  • You should copy the text that you don't process exactly, and when you detect some name, copy its value instead. I guess you also want to be careful when one value is also a previous name. Commented Feb 28, 2019 at 21:00

1 Answer 1

1

I will be so thankful if you can give me some ideas about the solution of the task

As OP is looking for ideas:

A key issue of that the pattern string and its replacement string may be of different lengths.

Read and process each line and save to another file.


Pseudo code:

Open file for reading
Open a temp file for writing
For each line
  if "define" found
    add to internal substitution list
  else 
    if a substitutable token found
      perform substitutions
    write line to temp file

close files
rename original file to tmp2
rename tmp file to original
if no errors anywhere
  delete tmp2

I'd expect about 100-200 lines of C code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.