0

I have a program specification that tells me I need to use lseek function to seek a position in a file and overwrite it with a value entered by the user. I know there might be better options that using lseek but this is what I got told to use.

This is what my test file looks like:

"Hello World from Tom!"

Let me give you some examples of test cases from my program:

  1. User input: "xxxxx". Result: "Hello xxxxx from Tom!"
  2. User input: "xx". Result: "Hello xxrld from Tom!"
  3. User input: "xxxxxxxx". Result: "Hello xxxxxxxxom Tom!"

How do I only replace the word "World" exactly, not more than it, not less than it.

This is a snippet of my program:

char replaceWord[10] = {'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', '\0'};
int writeFileDescriptor = open("TestFile.txt", O_WRONLY|O_RDONLY, 0700);
lseek(writeFileDescriptor, 6, SEEK_SET);


write(writeFileDescriptor, replaceWord, 5); // output will be case 1 from above
write(writeFileDescriptor, replaceWord, 2); // output will be case 2 from above
write(writeFileDescriptor, replaceWord, 8); // output will be case 3 from above

Please don't tell me not to use lseek function. This is a requirement that I was told to do. I cannot change the requirements. Besides that I am free to use what I want.

Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102
  • use lseek to get to the position next to World, copy the content till end of the file, rewind -> lseek to start of "World" -> write the replacement word -> write the copied contents. – abhilb Sep 26 '19 at 05:14
  • That makes a lot of sense! Thanks for your help @abhilb – Tom el Safadi Sep 26 '19 at 05:16
  • How would I deal with case 2 though, in which the word is shorter thant "World"? If I seek to the position and write the replacement word, "World" wouldn't be fully overwritten @abhilb – Tom el Safadi Sep 26 '19 at 05:19
  • World will be fully over written, but there might be data after "Tom!". Not sure! give it a try. – abhilb Sep 26 '19 at 05:28

0 Answers0