У меня проблемы с чтением и записью файла .dat. Файл administrator.dat был создан, но его невозможно прочитать, я не знаю почему.
Вот мой код:
struct Employee_t {
string account, password;
string name;
int age;
string address, phone, email;
};
запись. 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;
}
Упс. Прошу прощения за загрузку файла чтения чтения. Вот оно.