感谢5楼,也要感谢voidx和6楼,再次提醒了空间分配的错误。
根据各位大虾的意见,我修改了一下,并增加了结果输出:
方法一:
[view@localhost c]$cat emp.txt
fred|30|18677442345
barney|29|13766554321
jq|36|18977890987
[view@localhost c]$cat 3.c
#include<stdio.h>
struct emp{
char name[20];
long age;
char phone[12];
};
int main(){
int i,ret;
char str[50];
FILE * fp = fopen("emp.txt", "r");
struct emp a[3];
i=0;
while(fgets(str,50,fp)!=NULL){
if((ret=sscanf(str, "%[^|]|%ld|%s", a[i].name, &a[i].age, a[i].phone))<3){
fprintf(stderr,"sscanf() err!,ret=%d\n",ret);
fclose(fp);
exit(1);
}
i++;
}
for(i=0;i<3;i++){
printf("emp%d name is %s,age is %ld,phone is %s\n",i,a[i].name,a[i].age,a[i].phone);
}
fclose(fp);
return 0;
}
[view@localhost c]$cc -o 3 3.c
[view@localhost c]$./3
emp0 name is fred,age is 30,phone is 18677442345
emp1 name is barney,age is 29,phone is 13766554321
方法二:
[view@localhost c]$cat emp.txt
fred 30 18677442345
barney 29 13766554321
jq 36 18977890987
[view@localhost c]$cat 4.c
#include<stdio.h>
struct emp{
char name[20];
long age;
char phone[12];
};
int main(){
int i,ret;
char *str=(char *)malloc(50);
FILE * fp = fopen("emp.txt", "r");
struct emp a[3];
i=0;
while(fgets(str,50,fp)!=NULL){
if((ret=sscanf(str, "%s %ld %s", a[i].name, &a[i].age, a[i].phone))<3){
fprintf(stderr,"sscanf() err!,ret=%d\n",ret);
fclose(fp);
exit(1);
}
i++;
}
for(i=0;i<3;i++){
printf("emp%d name is %s,age is %ld,phone is %s\n",i,a[i].name,a[i].age,a[i].phone);
}
fclose(fp);
return 0;
}
[view@localhost c]$cc -o 4 4.c
[view@localhost c]$./4
emp0 name is fred,age is 30,phone is 18677442345
emp1 name is barney,age is 29,phone is 13766554321
emp2 name is jq,age is 36,phone is 18977890987
程序虽然简单,但是实用性很强,工作中要用到。以前习惯了用shell处理文本,用C倒是第一次。
[
本帖最后由 khaz 于 2011-4-23 11:08 编辑 ]