How can I delete part of the text inside a file? I've navigated to the place where I need to delete using seekg, and now I can't think of how to actually get rid of that part of the document.
Usually when doing this, you don't do it directly to the file.
First you are going to save the content of the file, using a input stream pointer (std:: ifstream), then manipulate with the content, and then use a output stream pointer (std:: ofstream) to write to the file again (use std::ios::trunc to overwrite file).
This shows how to open, read, manipulate and then write to the file again:
A better way would maybe be, instead of having to stream pointers (I/O), then only have one - the multi-streamed one (std::fstream). This was just to show how to use both types of the stream pointers. If you want to use std::fstream, then you have to use it in the same way, just remember to set the right I/O-flags each time. After you've set the flags once, using the constructor, you can always use the member, std::fstream::flags().Code:#include <iostream> #include <fstream> #include <string> #define FILENAME "test_file.txt" int main() { std::string fileContent; std::string fileContentTemporary; std::ofstream outputFile; std::ifstream inputFile; // Open the file, and read the content inputFile.open(FILENAME, std::ios::in); if(inputFile.is_open()) { while(getline(inputFile, fileContentTemporary)) fileContent += fileContentTemporary; inputFile.close(); } // Manipulate with the file content fileContent += " -- this was appended to the file"; // ... // Open the file, and write the manipulated content outputFile.open(FILENAME, std::ios::out | std::ios::trunc); if(outputFile.is_open()) { outputFile << fileContent; outputFile.close(); } return 0; }
Last edited by v0id; 05-10-2007 at 11:53 AM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks