Search code examples
c++filefstream

Reading and writing to files isn't working in C++


I am basically trying to reverse the contents of a text file. When I run this code, nothing happens. Code:

getArguments();
stringstream ss;
ss << argument;
string fileName;
ss >> fileName;
fstream fileToReverse(fileName);
if (fileToReverse.is_open()) {
    send(sock, "[*] Contents is being written to string ... ", strlen("\n[*] Contents is being written to string ... "), 0);
    string line;
    string contentsOfFile;
    while (getline(fileToReverse, line)) {
        contentsOfFile.append(line);
        line = "\0";
    }
    send(sock, "done\n[*] File is being reversed ... ", strlen("done\n[*] File is being reversed ... "), 0);
    string reversedText(contentsOfFile.length(), ' ');
    int i;
    int j;
    for(i=0,j=contentsOfFile.length()-1;i<contentsOfFile.length();i++,j--) {
        reversedText[i] = contentsOfFile[j];
    }
    contentsOfFile = "\0";
    fileToReverse << reversedText;
    fileToReverse.close();
    send(sock, "done\n", strlen("done\n"), 0);
}

fileName is created from user input, and I know that the file exists. It just doesn't do anything to the file. If anyone has any ideas that they would like to share that would be great.

UPDATE:

I now can write reversedText to the file but how can I delete all of the files contents?


Solution

  • In this particular case, when you have read all the input content, your file is in an "error state" (eof and fail bits set in the status).

    You need to clear that with fileToReverse.clear();. Your file position will also be at the end of the file, so you need to use fileToReverse.seekp(0, ios_base::beg) to set the position to the beginning.

    But I, just as g-makulik, prefer to have two files, one for input and one for output. Saves a large amount of messing about.