File stream condition. To Read if file has content else write info

What condition shoul i use?
if notepad/file has contents it will display the contents.

but if the notepad/file has no contents, it will automatically let the user enter first name, last name and address then write it on the file.
here's my code. I don't know what condition to use if the file is empty.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
#include<fstream>
using namespace std;

int main(){
   int size=20;
   char ans;
   char fname[size], lname[size], add[size];
   fstream fdata;
   fdata.open("Prog.txt");

   if(fdata){

             string file;
             getline(fdata,file);
             cout<<"Name: "<<file<<" ";
             getline(fdata,file);
             cout<<file<<endl;
             getline(fdata,file);
             cout<<"Address: "<<file<<endl;
             }

     else if(fdata.is_open()){
        cout<<"First Name: ";
        cin.getline(fname, size);
        cout<<"Last Name: ";
        cin.getline(lname,size);
        cout<<"Address: ";
        cin.getline(add,size);
        }
               fdata<<fname<<endl;
               fdata<<lname<<endl;
               fdata<<add<<endl;          

             fdata.close();
}
Last edited on
I don't know what condition to use if the file is empty.

Attempt a read from the file. If after the read eof() returns true, the file is empty.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Edited my code.
I'm sorry but how do you do it?
Topic archived. No new replies allowed.