简体   繁体   中英

Using fstream and fstream.eof. Working with files

I'm trying to make a programm, which will read the file, change specified word to symbols '@' and write back to same file. But I have problems with that.

1st question. It seems like I need to store file in buffer before writing it to the file. How should I do it?

2nd question: I cant understand why loop in this code never ends? It's about 200 words in that file, but I always get memory exception and i gets 10075.

int main(int argc, char* argv[]){
    char** temp = new char*[10000];
    int i = 0;
    fstream fTemp("D:\doc.txt", ios_base::in);
    while (!fTemp.eof()){
        temp[i] = new char[50];
        fTemp >> temp[i];
        temp[i][1] = '@';
        cout << temp[i] << endl;
        i++;
    }
    fTemp.open("D:\doc.txt", ios_base::trunc);
    for (int i = 0; i < sizeof(*temp); i++){
        fTemp << temp[i];
    }
    _getch();
}

First, you should use getline as your usage of eof is incorrect (eof bit is set only after failed read). Next, store the strings in a std::vector<string> . This will allow you to not care about memory management (current one is leaking) and provide a more flexible solution.

std::string buffer;
std::vector<string> data;
while(std::getline(fTemp,buffer)) {
      data.push_back(buffer);
}

The problem you probably have, is the incorrect eof() call, buy you should check you cout output to determine the problem with this code.

to store the data of file in a buffer, you can get the size of file and use the function read to get all file data. see this code:

// Load file in a buffer
ifstream fl(FileName);
fl.seekg(0, ios::end);
size_t len = fl.tellg();
char* fdata = new char[len];
fl.seekg(0, ios::beg);
fl.read(fdata, len);
fl.close();

in your case the same fstream that you used to open are being used to write without close the file before reopen.

Your loop never ends because it is a pointer, and it size isn't managed, the better way is get the size of file while it is open, in this case the size of file is the "size_t len".

to rewrite your code you can create another stream, see this code:

// Write File
ofstream flOut(FileName, ios_base::trunc);
flOut.write(fdata, len);
flOut.close();

between these two codes above, you can change the data of fdata, but what exactly you wanna make? is replace some word to symbol '@'? which word?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM