0

I create in C++ a function that write in file, by using stream. I want that file was overwrite when i call this code. When i add a fstream.peak, to know the next char, nothing was written in my text file. If they return -1, I want they write at X position in my text file. Here's my code (note that I begin in C++..) Thanks for the future help! :)

fstream myFStream = myFStream.open("./myFile.txt,  ios::in |ios::out | ios::trunc | ios::binary);
int positionFile = 2;
myFStream.seekp(positionFile, ios::beg);
char textToWrite[10] = "";
textToWrite = "mytext";

**// [don't write when I add this IF]
if (myFStream.peek() > 0) 
    { positionFile += 15; }**

 myFStream.write(textToWrite, 6);
 myFStream.close();
SurveyVisual
  • 27
  • 1
  • 8
  • 3
    Unclear what you want to do. `ios::trunc` discards the contents of the file, I don't think you want that. – 001 Nov 30 '16 at 15:43
  • after the failed `peek` your stream is in an error state, so writing does not work – Karsten Koop Nov 30 '16 at 15:43
  • In addition to the comment by @JohnnyMopp, even if the write succeeded, everything after the first character in `textToWrite` is nonsense, so writing it out is pointless. – Pete Becker Nov 30 '16 at 15:44
  • @JohnnyMopp : Yes, I want overwriting my file. – SurveyVisual Nov 30 '16 at 15:49
  • @KarstenKoop When peek() failed, my fstream is like "broken" and I can't write nothing new in my file? If I want to know if they had a char at X position and they return -1, how can I do that? – SurveyVisual Nov 30 '16 at 15:50
  • don't set `ios::trunc` – Karsten Koop Nov 30 '16 at 15:53
  • I'm having this same issue. I've opened the file as an fstream with `ios::in`, `ios::out` and `ios::binary`, peek the first byte which returns the correct value then all subsequent writes fail unless I call seek in which case writes start to work again. I have no idea what the issue is; all bits are the same value before and after the call to peek – vane Apr 23 '20 at 20:34

0 Answers0