将 fscanf 传递给结构
我正在尝试打开一个文件并传递给 struct
,我正在使用带有循环的 fscanf()
,但它只保存一个 struct最后阅读:
想象一个文件:
JR John Rambo 24353432
JL John Lennon 6435463
我正在使用这段代码:
typedef struct people{
char code[10];
char name[100];
long telephone;
}PEOPLE;
int read(PEOPLE people[], int n_p){
char temp;
FILE *fp;
fp=fopen("example.txt","r");
if(fp==NULL){
printf("Error\n");
return -1;
}
while(!feof(fp)){
fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].name,
&people[n_p].telephone);
}
}
问题是他只保存文件的最后一行......我应该做一个if cicle吗?
另一个问题是如何分隔类似的文件但用“;”
I'm trying to open a file and pass to struct
, I'm using fscanf()
with a loop, but it only saves one the struct
the last read:
Imagine a file:
JR John Rambo 24353432
JL John Lennon 6435463
I'm using this code:
typedef struct people{
char code[10];
char name[100];
long telephone;
}PEOPLE;
int read(PEOPLE people[], int n_p){
char temp;
FILE *fp;
fp=fopen("example.txt","r");
if(fp==NULL){
printf("Error\n");
return -1;
}
while(!feof(fp)){
fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].name,
&people[n_p].telephone);
}
}
The Problem is that he only saves the last line of the file...Should I do a if cicle??
Another question is how can I separate a similar file but with ";"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,当您在
fscanf()< 中仅传递 3 个参数时,您将扫描 3 个字符串 (
%s
) 和 1 个整数 (%d
)。 /代码>。您可以在您的struct
中添加一个char first_name[50];
,然后执行以下操作:您始终
fscanf()
该文件,直到您没有更多内容为止读取(由于!feof(fp)
因为 while。所以在最后一个people[n_p]
变量中,文件的最后一行将被保存。您可以从
read()
中删除while
并将FILE *
作为参数添加到函数中,这样您就不会打开文件每次调用read()
时,可能会出现这样的情况:
要使用
;
作为分隔符,您可以将fscanf()
更改为:编辑我编写了上面的代码,可以在此处找到,它与此< a href="http://pastebin.com/ug2BMgu6" rel="nofollow">example.txt 文件 作为输入。
First of all, you are scanning for 3 strings (
%s
) and one int (%d
) when you pass only 3 parameters in yourfscanf()
. You could add achar first_name[50];
in yourstruct
and then do:You always
fscanf()
the file until you have nothing more to read (due to the!feof(fp)
because of the while. So in the lastpeople[n_p]
variable the last line of the file will be saved.You could remove the
while
fromread()
and also add theFILE *
as a parameter to the function so that you don't open the file each time you callread()
.Something like this maybe:
For using the
;
as a separator you can changefscanf()
to this:EDIT I wrote the above code which can be found here and it works fine with this example.txt file as input.
看来您没有更改 n_p 变量。您需要某种变量来跟踪您正在更新的 people[] 数组的索引。
此外,希望您有足够大的人员数组来保存文件中的所有条目。
It looks like you're not changing the n_p variable. You need some sort of variable to keep track of which index of the people[] array you're updating.
Additionally, hopefully you've got a large enough people array to hold all the entries in the file.