使用fscanf进行文件扫描

时间:2014-11-24 09:43:30

标签: c

我的fscanf存在问题,我的结构数组会在customer[i].Acc_No中同时保存帐号和姓名,并重复保留我的姓名customer[i].fullname。 第一次扫描没有问题,从第2次开始。为什么呢?

示例:

id:FAFB1234 name:LEE FU HUA

customer[0].Acc_No store "FABE1234LEE FU HUA"

我的代码:

information customers[10];
int i;
FILE *fptr;

fptr=fopen("Customer.txt","r");
file_check(fptr);

i=0;
while(!feof(fptr))
{
    fscanf(fptr,"%[^|]|%[^|]|%[^|]|%d %d %d %lf %d %d %d",customers[i].Acc_No,customers[i].fullname,customers[i].address
    ,&customers[i].birthday.day,&customers[i].birthday.month,&customers[i].birthday.year,&customers[i].balance_owning,&customers[i].last_trans.day
    ,&customers[i].last_trans.month,&customers[i].last_trans.year); 
i++
}

我的txt文件:

FAFB1234|LEE FU HUA|NO38 JALAN BUNGA TAMAN LAWA 48235 SHAH ALAM,SELANGOR|18 09 1995 0.00 1 9 2014
FEBE2014|LOW CHU TAO|A-111 JALAN YING TAMAN YANGYANG 56981 WANGSA MAJU,KUALA LUMPUR|30 03 1996 0.00 1 9 2014
FAFB2014|JERRY CHOW|I-414 JALAN MATINI TAMAN ASRAMA PENUH 56327 SETAPAK,KUALA LUMPUR|15 02 1995 0.00 1 9 2014
FEBE1001|LEE WEI KIET|NO 49 JALAN 5/6 TAMAN BUNGA SELATAN 48752 HULU SELANGOR,SELANGOR|06 09 1996 0.00 1 9 2014
FAFB1001|HO HUI QI|NO 888 JALAN 65/79 TAMAN TERLALU BESAR 75368 KUANTAN,PAHANG|26 04 1996 0.00 1 9 2014

1 个答案:

答案 0 :(得分:1)

scanf和家人可以直接从流中读取非常不可预测的结果。如果解析失败,其他一切都必然会失败。

使用scanf和系列时,建议您始终在缓冲区上逐行fgets然后sscanf读取数据。

试试这个:

information customers[10];
FILE *fptr;

fptr=fopen("Customer.txt","r");
file_check(fptr);


// buffer to read line by line
char line[0x1000];
int i = 0;
while (fgets(line, sizeof(line), fptr)) {
    information this_customer; // buffer for surrent customer
    memset(&this_customer, 0, sizeof(this_customer));

    int num_entries_read = sscanf(line,"%[^|]|%[^|]|%[^|]|%d %d %d %lf %d %d %d",this_customer.Acc_No,this_customer.fullname,this_customer.address
        ,&this_customer.birthday.day,&this_customer.birthday.month,&this_customer.birthday.year,&this_customer.balance_owning,&this_customer.last_trans.day
        ,&this_customer.last_trans.month,&this_customer.last_trans.year);

    if (num_entries_read == 10) { // all fields were successfullt matched
        // copy this customer into the array
        customers[i] = this_customer;
        i++;
    } else {
        fprintf(stderr, "failed to parse line: %s", line);
    }
}