50 likes | 183 Views
Chapter 8. Files: Electronic Storage. How to work with files. #include <fstream> To write to a file: ofstream fout("output.txt"); fout << "Hi There"; fout.close(); To read from a file: ifstream fin("input.txt"); fin >> s; // or fin.getline(s,80) to get complete line fin.close();.
E N D
Chapter 8 Files: Electronic Storage
How to work with files • #include <fstream> • To write to a file: • ofstream fout("output.txt"); • fout << "Hi There"; • fout.close(); • To read from a file: • ifstream fin("input.txt"); • fin >> s; // or fin.getline(s,80) to get complete line • fin.close();
void main(){ char s[100]; ofstream fout("data.txt"); if(fout){ fout << "Hi There!"; fout.close(); } ifstream fin("data.txt"); if(fin){ fin >> s; cout << s; fin.close(); } }
How to refer to disk files • c:\\users\\lubo\data.txt • \\ because \ is a special character
Reading all the words from a file int main(){ char s[100]; ifstream fin("data.txt"); if(fin){ while(!fin.eof()){ fin >> s; cout << s; } fin.close(); } }