+ 3

Seekg() in data files

In this code f.seekg(0) in line 27 only works when I include ios:: trunc also in line 14 Why?? As far as I have learnt about data files trunc is used for totally different purpose copy this as input 👇 123 Abc N https://code.sololearn.com/ckjTwPvn0CeR/?ref=app

26th Mar 2019, 11:29 AM
Saurabh Tiwari
Saurabh Tiwari - avatar
8 Respuestas
+ 9
Some `basic_fstream` flags and their equivalents to `fopen` modes and their meanings: (ios::in) == "r" == read == Open file for input operations. The file must exist (ios::out) == "w" == write == Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. (ios::in | ios::out) == "r+" == read/update == >>>Open a file<<< for update (both for input and output). >>>The file must exist<<<. (ios::in | ios::out | ios::trunc) == "w+" == write/update == >>>Create an empty file<<< and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file. When the program gets executed for the first time in "r+" mode, the `while (f)` fails because there's no file on the disk. However, putting the mode into "w+" will create the file and further if you change the mode back to "r+" there wouldn't be any problem as emphasized on the description. _____ http://www.cplusplus.com/reference/cstdio/fopen/ https://stackoverflow.com/questions/15084007/why-does-ofstreamlog-txt-iosappiostrunc-always-fail
26th Mar 2019, 3:24 PM
Babak
Babak - avatar
+ 4
Where are you running this?
26th Mar 2019, 12:10 PM
John Wells
John Wells - avatar
+ 3
If you mean by it only works that the previous non over written contents of the file disappears, you are right. trunc empties the file. Without it, if the file has six records and you rewrite the first two, the remaining four are still there.
26th Mar 2019, 11:55 AM
John Wells
John Wells - avatar
26th Mar 2019, 5:18 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 2
C++ Soldier (Babak) Baptiste E. Prunier I hope I didn't disturb you by mentioning you
26th Mar 2019, 11:31 AM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 2
John Wells no no I create a record and want to print it So I have to relocate the pointer at the beginning using seekg() but it is not working as it prints nothing consider it to be a new program in which I have to create a file and print it
26th Mar 2019, 12:07 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 1
Codeblocks it is not working even on sololearn
26th Mar 2019, 12:11 PM
Saurabh Tiwari
Saurabh Tiwari - avatar
+ 1
Your iostatus is failbit so seekg doesn't work. Not sure why your write has failed. I've never really used streams only C basic file IO so it will take me a bit.
26th Mar 2019, 1:03 PM
John Wells
John Wells - avatar