【发布时间】:2016-12-13 16:36:14
【问题描述】:
我正在处理的程序应该从预先存在的文本文件中提取数据,编辑数据,然后将其重写到新的文本文件中。我已经完成了大部分工作,但它不会将任何扫描的数据存储到我的阵列中。当我调用我的打印到文件功能(我相当肯定它可以正常工作)时,没有任何内容打印到新文件中。
整个代码文件相当长,所以我只包括其中的一部分。如果您需要任何澄清,请告诉我;任何建议或想法都会有很大帮助!提前谢谢!
它应该从中提取的文件具有默认格式
Name:\n\t Hours Worked: \n\tWeekly Pay: \n\tTaxes Paid: \n\tTake-home Wage:
代码
// in main (already declared and initialized all variables
printf("Please enter the name of the text file you'd like to read from: ");
scanf(" %s",fileName);
fp= (fopen(&fileName, "r+"));
if (fp ==NULL)
{
printf("Unable to open %s", fileName);
exit(1);
}
for(int i=0; i<10; i++){
loadFromFile(&employeeInfo[i],fp);
}
fclose(fp);
break;
int loadFromFile(struct Employee *employee,FILE *fp){
static int employeeNumb;
fscanf(fp, " %*[^:]: %s", employee->name);
if ((*employee).name==feof(fp))
printf("fscanf did not store properly");
fscanf(fp," %*[^:]: %f", &employee->hoursWorked);
fscanf(fp," %*[^$]$ %f", &employee->weeklyPay);
fscanf(fp, " %*[^$]$ %f", &employee->taxesPaid);
fscanf(fp, " %*[^$]$ %*s");
employeeNumb++;
return employeeNumb;
}
编辑:添加了我的打印到文件功能
void saveToFile(struct Employee employee[], int employeeNumb){
FILE *fp;
char newFile[40];
printf("Please enter the name of the text file you'd like to create or overwrite: ");
scanf(" %s",newFile);
fp= fopen(newFile, "w+");//r+ if do NOT want to overwrite or a+ if append
if (fp ==NULL)
{
printf("Unable to open %s", newFile);
exit(1);
}
for(int i=0; i<employeeNumb; i++){
printToFile(fp,&employee[i]);
}
fclose(fp);}
void printToFile(FILE *fp,struct Employee *employee){
fprintf(fp, "\nName: %s", (*employee).name);
fprintf(fp,"\n\tHours Worked: %g", (*employee).hoursWorked);
fprintf(fp,"\n\tWeekly Wage: $%.2f", (*employee).weeklyPay);
fprintf(fp, "\n\tTaxes Paid: $%.2f", (*employee).taxesPaid);
fprintf(fp, "\n\tTake-home Wage: $%.2f", ((*employee).weeklyPay)-(*employee).taxesPaid);
}
编辑 2:添加结构定义
struct Employee {
char name[40];
float weeklyPay;
float hoursWorked;
float taxesPaid;};
【问题讨论】:
-
fopen(&fileName, "r+")-->fopen(fileName, "r+") -
fscanf(fp," %*[^:], %f", employee->weeklyPay);,例如,期望读取一个逗号(并且不会读取冒号或美元符号)......当你应该传递一个指针时,你正在传递一个float到一个。 -
另外,
fscanf()的%s不会读取包含空格的字符串(只会读取第一个单词),所以如果你有例如。您的姓名字段中的名字和姓氏会出现问题。此外,您的读取代码预计每条记录恰好有四行/字段,因此希望输出中的最后一个字段不在您的输入文件中。 -
考虑
fscanf(fp, " %*[^:]: %s", employee->name);。当输入以':'开头时会发生什么? -->employee->name中没有保存任何内容,':'没有被消耗。当输入位于文件末尾时会发生什么?以前的feof()没有帮助。employee->name中没有保存任何内容,因此第 1 步 - 检查fscanf()的结果与预期的返回值(在这些情况下通常为 1)。 -
feof()并不完全表示文件结束...它表示先前的读取失败是否是由文件结束(种类)引起的。您需要检查来自fscanf()的返回以查看它是否读取了字段...如果fscanf()返回 EOF,那么您可以使用feof()如果您想知道它是否到达文件末尾或点击一些其他错误。
标签: c arrays file struct scanf