c++ - Why I can't read from file using "file_ptr>>variable" in my program? -


in following program trying understand how read , write files.

#include<iostream> #include<fstream> using namespace std; int main() {     fstream myfile;     string str1;     myfile.open("h:/input_file.txt");     if(myfile.is_open())     {        myfile<<"test1 writing files"<<" ";     myfile>>str1;     cout<<str1<<endl;     }     return 0; } 

why don't output on console though "test1 writing files" written file?

the file need opened both read , write (i'm sorry, ignore that; fstream opened both read & write default). after writing (and flushing output), need seekg() beginning of file, or trying read comes after last thing wrote, of course nothing.

myfile<<"test1 writing files"<<" "; myfile.flush();  myfile.seekg(0, ios_base::beg); myfile>>str1; 

seekg used change position read (get) file. seekp used change position write (put) file.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -