我是编程的初学者,我得到了一些帮助。我有一个文件,必须将此文件的数据(名称,地址,序列号,功能)分配给数据结构。我怎么能这样做?
#include<stdio.h>
typedef struct
int age;
char addres[50];
long serial_num;
char function[25];
} pers;
main(){
int i, n, a1;
char num_tot[21]= "Number of person: ";
FILE *f1;
//pers p[n];
f1=fopen("bd.txt", "r");
while(!feof(f1)){
if(fread(&a1, sizeof(f1),1,f1)==num_tot[21]) //bad idea
{
}
}
//文件
Number of person: 3
1.Name: Andrei Ungureanu
Age: 27
Addres: Chisinau, str. Vasile Alexandri 94a
Serial number: 245578
Function: secretary
2.Name: Boris Macari
Age: 24
Addres: Chisinau, str. 27 Martie 1918 56
Serial number: 787791
Function: general auditor
3.Name: Corina Lupu
Age: 43
Adresa: Chisiau, str. Liviu Deleanu 9
Serial number: 983345
Function: general manager
答案 0 :(得分:0)
我只是分享我的代码我已写到您的问题
请记住,我的代码很大程度上取决于文件的一般结构!
我希望这会对你有所帮助
#include <stdio.h>
#include <string.h>
using namespace std;
typedef struct
{
int age;
char addres[50];
long serial_num;
char function[25];
} pers;
int main()
{
FILE *f1;
f1 = fopen("bd.txt", "r+");
int n = 0;
char line[100];
char ch;
int i = 0;
while((ch = fgetc(f1)) && ch!='\n')
{
line[i++] = ch;
}
for(int k = 18 ; k < i; k++)
{
n = n*10 +(line[k]-'0');
}
pers p[n];
memset(line , '\0', i);
i = 0;
for(int m = 0; m < n; m++)
{
while((ch = fgetc(f1)) && ch!='\n') //blank line
{
continue;
}
while((ch = fgetc(f1)) && ch!='\n') //line of name(we don't need this data)
{
continue;
}
/////////////
while((ch = fgetc(f1)) && ch!='\n') //line of age
{
line[i++] = ch;
}
int j = 5;
p[m].age = 0;
while(line[j] != ' ' && line[j] != '\0')
p[m].age = p[m].age*10 + (line[j++]-'0');
memset(line , '\0', i);
i = 0;
/////////////
while((ch = fgetc(f1)) && ch!='\n') //line of address
{
line[i++] = ch;
}
j = 8;
while(j != i)
p[m].addres[j-8] = line[j++];
memset(line , '\0', i);
i = 0;
//////////////
while((ch = fgetc(f1)) && ch!='\n') //line of serial_number
{
line[i++] = ch;
}
j = 15;
p[m].serial_num = 0;
while(line[j] != ' ' && line[j] != '\0')
p[m].serial_num = p[m].serial_num*10 + (line[j++]-'0');
memset(line , '\0', i);
i = 0;
//////////////
while((ch = fgetc(f1)) && ch!='\n' && ch != EOF) //Line of function
{
line[i++] = ch;
}
j = 10;
while(j!=i)
p[m].function[j-10] = line[j++];
memset(line , '\0', i);
i = 0;
}
// for (int m = 0; m < n; m++)
// {
// printf ("%s *** %d *** %s *** %ld\n", p[m].addres , p[m].age , p[m].function , p[m].serial_num);
// }
return 0;
}