gpt4 book ai didi

c - 将结构写入文本文件

转载 作者:行者123 更新时间:2023-12-02 15:28:27 25 4
gpt4 key购买 nike

所以我最近掌握了结构的窍门,终于对数组感到满意,现在我必须处理我的教授希望我能够存储 100 万个结构(工资单记录)的文件,而且我很确定这么大的数组会崩溃我的程序。所以我对如何将结构备份到 txt 文件并在启动时将它们上传回我的程序感到困惑。文字会不会乱七八糟?这是我需要放入文件中的程序的主要部分。它基本上使用结构制作工资单记录。所以我只是想知道任何人都可以给我提示将其发送到文本文件中

void payRollAdd(PAYROLL employee[], long int *pCounter){    
int userinput;
do{
printf("Enter Employee Name:\n");
fgets(employee[*pCounter].name, 40, stdin);
printf("Please Enter the paydate(mmddyyyy):\n");
scanf_s("%02d%02d%d", &employee[*pCounter].payDate.month, &employee[*pCounter].payDate.day, &employee[*pCounter].payDate.year);
printf("Enter Employee Age:\n");
scanf_s("%d", &employee[*pCounter].age);
printf("Enter Employee Hours Worked\n");
scanf_s("%f", &employee[*pCounter].hrsWorked);
printf("Enter Employee Hourly Wage:\n");
scanf_s("%f", &employee[*pCounter].hrlyWage);
printf(" Employee Data \n");
printf("Name: %s\n", employee[*pCounter].name);
printf("Age: %d\n", employee[*pCounter].age);
printf("Pay Date: %02d/%02d/%d:\n", employee[*pCounter].payDate.month, employee[*pCounter].payDate.day, employee[*pCounter].payDate.year);
printf("Hours Worked: %0.2f\n", employee[*pCounter].hrsWorked);
printf("Hourly Wage: $%0.2f\n", employee[*pCounter].hrlyWage);


if (employee[*pCounter].hrsWorked > 40.00){
float temp = 40.00;
employee[*pCounter].regPay = temp * employee[*pCounter].hrlyWage;
printf("Regular pay: $%0.2f\n", employee[*pCounter].regPay);
}
else
{
employee[*pCounter].regPay = employee[*pCounter].hrsWorked * employee[*pCounter].hrlyWage;
printf("Regular pay: $%0.2f\n", employee[*pCounter].regPay);
}
if (employee[*pCounter].hrsWorked > 40.00){
float temp2 = 0.00;
temp2 = employee[*pCounter].hrsWorked;
temp2 -= 40.00;
employee[*pCounter].otPay = temp2 * `(employee[*pCounter].hrlyWage + (employee[*pCounter].hrlyWage / 2.00));`
printf("OT pay: $%0.2f\n", employee[*pCounter].otPay);
}
else
{
employee[*pCounter].otPay = 0;
printf("OT pay: $0\n");
}
employee[*pCounter].totalPay = employee[*pCounter].regPay + employee[*pCounter].otPay;
printf("Total Pay: $%0.2f\n", employee[*pCounter].totalPay);

最佳答案

可以结合使用fseek、fwrite和fread来读写和查找文件中的结构:

fseek(fp,0L,SEEK_END);
fwrite(&employee,sizeof(employee),1,fp);

你可以做类似的事情来读取记录:

fseek(fp,sizeof(employee) * recno,SEEK_SET);
fread(&employee,sizeof(employee),1,fp);

检查返回码!

关于c - 将结构写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29159526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com