1

I need to remove all digits and spaces from a file but I want to do it without rewriting the file. I wrote the following code: `

#include <iostream>
#include <fstream>
#include <regex>

using namespace std;

int main() {
    std::fstream fs("./input.txt", ios::in|ios::out);
    string line;

    while (getline(fs, line)) {
        fs.seekp(-(1+(long)line.length()), ios::cur);

        size_t line_length = line.length();

        line = regex_replace(line, regex("\\d+"), "");
        line = regex_replace(line, regex(" "), "");

        char *writable = new char[line.length()];
        std::copy(line.begin(), line.end(), writable);
        fs.write(writable, line_length);

        fs.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return 0;
}

` and it work but it leaves null-terminator \0 at the end of each line where there were spaces or numbers. I also tried deleting numbers and spaces character by character, using fstream::write("", 1), but instead of remove, \0 were written. Please explain how it works and how to fix it.

  • It's hard to truncate a file to the new size after removing data. The standard library doesn't offer any tool that I'm aware of to do the job. – user4581301 Jul 17 '21 at 06:52
  • Ok, then I should rewrite the file and there are no other ways to do it using only stl? Thanks @user4581301 – Igor Shishkin Jul 17 '21 at 06:57
  • There are OS specific ways to do it, but not when using C or C++ library functions. – user4581301 Jul 17 '21 at 07:01
  • @user4581301 Can you provide a pointer to any such way? I didn't know it was possible. – Costantino Grana Jul 17 '21 at 07:15
  • _using fstream::write("", 1), but instead of remove, \0 were written._ `""` is a string literal which results in a `char[1]` with the zero-terminator (`'\0'`) only. `fstream::write("", 1)` writes this 1 byte (with the zero-terminator) to the file. So, what you describe is exactly what should be expected, doesn't it? You cannot erase characters from a file (as well as you cannot do it in a C array). All you can do is to overwrite bytes with the following which results in the effect of shifting the trailing contents. – Scheff's Cat Jul 17 '21 at 08:32
  • Do you want to replace the numbers with spaces or do you want to shorten the file by closing the gap that removing the number produces? – Galik Jul 17 '21 at 08:39
  • 1
    @Scheff's Cat thanks, now I understand. I have to overwrite the characters, offset all following chars and truncate the file. Right? – Igor Shishkin Jul 17 '21 at 09:58
  • @Galik I want to shorten the file. Now I will try follow Scheff's Cat's advice – Igor Shishkin Jul 17 '21 at 10:01

0 Answers0