這個程序,我正在爲類創建一個EMPLOYEE記錄文件。我創建了兩個結構。一個叫僱員,一個叫日期。 EMPLOYEE結構有一個char數組,一個int,六個float值和DATE(另一個Struct)。 DATE結構只有三個int值(月,日,年)。讀取,填充和寫入結構數組到一個二進制文件
我創建了一個名爲person [1000]的EMPLOYEE類型的數組。
這是我的代碼,我不斷收到一個調試斷言失敗的錯誤在視覺工作室指向fwrite.c表達式:(流!= NULL)。我相信這與我的fread或fwite有關,因爲我從來沒有試圖存儲結構。
這個函數的開始點是填充數組,如果文件存在並且不是空的,那麼當用戶開始將數據存儲到數組時,下標被更新。我知道這裏可能還有其他一些問題,但首先要做的事情就是閱讀和寫作部分。再次
感謝,
邁克
void loadPayRoll(EMPLOYEE person[], int *i)
{
char sValidate[5] = "exit";
FILE *f;
int count = 0;
f = fopen("emplyeeRecords.bin", "rb");
if(f){
while(fread(&person[*i], sizeof(person), 1, f) > 0){
(*i)++;
}
fclose(f);
}
else {
while (strcmp(sValidate, person[*i].name)) {
fopen("employeeRecords.bin", "ab+");
printf("Please enter name or type exit to return to main menu: ");
scanf("%s", person[*i].name); //must use the '->' when passing by by refrence, must use '&' sign
flush;
if (!strcmp(sValidate, person[*i].name))
break;
printf("\nPlease enter age of %s: ", person[*i].name);
scanf("%i", &person[*i].age);
flush;
printf("\nPlease enter the hourlyWage for %s: ", person[*i].name);
scanf("%f", &person[*i].hourlyWage);
flush;
printf("\nPlease enter the hours worked for %s: ", person[*i].name);
scanf("%f", &person[*i].hoursWkd);
if (person[*i].hoursWkd > 40) {
person[*i].regPay = person[*i].hoursWkd * 40;
person[*i].otHoursWkd = person[*i].hoursWkd - 40;
person[*i].otPay = person[*i].otHoursWkd * (person[*i].hourlyWage * 1.5);
person[*i].totalPay = person[*i].regPay + person[*i].otPay;
}
else {
person[*i].totalPay = person[*i].hoursWkd * person[*i].hourlyWage;
}
flush;
printf("\nEnter 2 digit month: ");
scanf("%i", &person[*i].payDate.month); //must use the '->' when passing by by refrence, must use '&' sign
flush;
printf("\nEnter 2 digit day: ");
scanf("%i", &person[*i].payDate.day); //must use the '->' when passing by by refrence, must use '&' sign
flush;
printf("\nEnter 4 digit year: ");
scanf("%i", &person[*i].payDate.year); //must use the '->' when passing by by refrence, must use '&' sign
flush;
fwrite(&person[*i], sizeof(person), 1, f);
fclose(f);
(*i)++;
}
}
}//end function loadPayRoll
不知道爲什麼我是一個指針。它看起來像你用它作爲索引?它應該是一個普通的整數。除此之外,請閱讀這裏:http://stackoverflow.com/questions/3711233/is-the-struct-hack-technically-undefined-behavior – 2013-02-22 21:52:31
沒有必要打開和關閉循環內的文件。在循環之前打開它並關閉它。 – 2013-02-22 21:54:35
我是一個指針,因爲它被另一個函數傳遞,但現在我想到了它。這可能不是必要的,因爲我不認爲另一個函數需要知道結尾的下標值。 – 2013-02-22 22:18:50