0

I have some problems with read and write file .dat. The file administrators.dat was created but impossible to read it, I don't know why.

Here is my code:

struct Employee_t {
    string account, password;
    string name;
    int age;
    string address, phone, email;
};

writing.cpp

int main () 
{ 
    FILE *outfile; 

    // open file for writing 
    outfile = fopen ("person.dat", "w"); 
    if (outfile == NULL) 
    { 
        fprintf(stderr, "\nError opend file\n"); 
        exit (1); 
    } 

    Employee_t input1 = {"BQTshadow", "123456", "ThieuBQ", 45, "Tu Xuong", "01294124", "asfas@yahoo.com.vn"}; 
    Employee_t input2 = {"Bravo", "123123", "dhoni", 26, "TranVV", "124123124124", "awfasf@asdas.com.vn"}; 

    // write struct to file 
    fwrite (&input1, sizeof(Employee_t), 1, outfile); 
    fwrite (&input2, sizeof(Employee_t), 1, outfile); 

    if(fwrite != 0)  
        printf("contents to file written successfully !\n"); 
    else 
        printf("error writing file !\n"); 

    // close file 
    fclose (outfile); 

    return 0; 
} 

read.cpp

int main () { 

    FILE *infile; 
    struct Employee_t input; 


    // Open person.dat for reading 
    infile = fopen ("administrators.dat", "r"); 
    if (infile == NULL) { 
        fprintf(stderr, "\nError opening file\n"); 
        exit (1); 
    } 

    // read file contents till end of file 


    while(fread(&input, sizeof(struct Employee_t), 1, infile)) 

        cout << input.account << " " <<input.password << " "<< input.name << " " <<  input.age <<" " << input.address << " " << input.phone << " " << input.email << endl ;

    // close file 
    fclose (infile); 
    system("pause") ; 

    return 0; 
}

int main () { 

FILE *infile; 
struct Employee_t input; 


// Open person.dat for reading 
infile = fopen ("administrators.dat", "r"); 
if (infile == NULL) { 
    fprintf(stderr, "\nError opening file\n"); 
    exit (1); 
} 

// read file contents till end of file 


while(fread(&input, sizeof(struct Employee_t), 1, infile)) 

    cout << input.account << " " <<input.password << " "<< input.name << " " <<  input.age <<" " << input.address << " " << input.phone << " " << input.email << endl ;

// close file 
fclose (infile); 
system("pause") ; 

return 0; 
}

Ops.. I'm sorry for forgeting upload reading file. Here it is.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Your struct doesn't contain POD (Plain old data) so you can just copy the bits. See https://en.cppreference.com/w/cpp/named_req/PODType Also look up TriviallyCopyable – doug Mar 18 '20 at 04:10
  • You can't save and restore non trivially class data this way. Use a serializing library to do this. https://stackoverflow.com/questions/234724/is-it-possible-to-serialize-and-deserialize-a-class-in-c – doug Mar 18 '20 at 15:57

0 Answers0