[C++ fstream write] How do I insert \0 in the last letter when I write a string?

Asked 2 years ago, Updated 2 years ago, 21 views

The code below is the code that replaces the word Customer written on the file with the word Admin.

The end may not have been handled well with NULL, but it overlaps with the existing text (Customer) and becomes Adminmer.

Because Customer has more characters, there is no problem with changing from Admin to Customer.

If the number of characters before changing is this small than the number of characters you want to change, what should you do when the letters overlap with the existing ones?

I think we need to insert the NULL properly. I don't know what to do.

(Admin + not spacing, but just Admin.)

    fstream fs;
    fs.open(getLoginedID() + ".dat", /*fstream::binary |*/ fstream::in | fstream::out);

    string str((istreambuf_iterator<char>(fs)), istreambuf_iterator<char>());
    size_t pos = str.find("Customer");

    if (pos != string::npos) {
        cout << "string found at position: " << int(pos) << endl;
        fs.seekp(pos);
        fs << "\nAdmin";      
        fs.put('\0');
        //fs.write("\nAdmin\0", 7); does not work this way either
    }
    fs.close();
}

c++

2022-09-22 11:38

1 Answers

Performance is not very important, so we solved it as follows. The code works as intended, but I don't know if it has any other problems Haha

ifstream userInfoFile;
    ofstream tempFile;
    string strTemp;
    try {
        openFileToRead(userInfoFile, (id + ".dat").c_str());
        openFileToWrite(tempFile, "temp.dat");
        while (userInfoFile >> strTemp)
        {
            if (strTemp == "Customer") {
                strTemp = "Admin";;
            }
            strTemp += "\n";
            tempFile << strTemp;
        }
    }
    catch (string err) {
        cerr << err << endl;
        exit(EXIT_FAILURE);
    }
    userInfoFile.close();
    tempFile.close();
    remove((id + ".dat").c_str());
    rename("temp.dat", (id + ".dat").c_str());


2022-09-22 11:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.