C++ File I/O

Recommended Posts

Nokturnal    190
I have a file which is (to an extent) structured. What i need to do is look for a particular string (A) in the file , pick up the next string (B) besides it.... (seperated by spaces or tabs , not consistent) & replace the string (B) with a new string. I tried Using fopen , strtok to get the identifier, and look for the string (A) in the file. The problem being , i was unable to fputs , the string (B). Random seek functions donot help as i dont know the exact offset where the identifer will be encountered. Hence the search needs to go till EOF.Any help is appreciated. ex file
AA  BB
CC    DD
AA  MM

O/p
AA KK
CC   DD
AA KK



Share on other sites
Evil Steve    2017
If the data you're searching for isn't the same length as the data you're replacing it with, you'll have to read the whole file in and write it out again. Files are just streams of bytes, there's no concept of ends of lines, and there's no ability to insert data into a file, you can only overwrite existing data or extend the file.

Doesn't really answer your question, but it's something to beware of befire you start.

Share on other sites
Nokturnal    190
Thanks for the prompt reply Evil Steve!
That maynot have been what i was looking for, but you have just given me a new approach! What i'll be trying out is reading the entire file in a array , searching each line for the identifier , if found , modify the identifier to suit the needs & store it. At the end of day , just dump it all into a new file! :)

Share on other sites
cshowe    360
Is there a reason you're trying to do this with C++? This sort of thing is FAR more suited to a scripting language like awk or python.

Share on other sites
Nokturnal    190
Hi cshowe,
At the moment i am constrained by the environment i am working in. I am not familiar with AWK , but i had just posted a simplified example of what i need to do above. I will be puting the 2nd string through a number of operations before i rewrite it. I am not sure if AWK offers such a functionality.Something , i'll look up :)

Cheers!

Share on other sites
_goat    804
If you're going to read the whole thing then spit it out, use the C++ streams, rather than the C fopen, fread, etc functions. std::getline would be very helpful here. And a simple string tokeniser to separate on whitespace.