假设我的Client.txt文件如下所示。Client.txt文件图片
1111
Name One
Email.email.1
111-111-1111
2222
Name Two Two
Email.email.2
222-222-2222
3333
Name Three Three
Email.email.3
333-333-3333
Client txt文件包含客户的id、姓名、电子邮件和电话号码。
现在的任务是从Client文件中读取,并将id、姓名、电子邮件和电话号码保存到一个名为Client的结构体中。从这个客户机文本文件中,我将创建三个结构体值,它们将被推入到结构体列表中。
但是由于我刚刚学习如何使用fscanf,并且在尝试实践fscanf时,我将任务缩小为:如何从文本中读取并初始化第一个客户端的值?
这是我尝试的。
int main(void){
FILE *fPtr;
if((fPtr = fopen("Client.txt"), "r") == NULL){
puts("File could not be found.");
}
else{
//First Client
int clientId;//1111
char clientName[30];//Name One
char clientEmail[30];//Email.email.1
char clientPhone[30];//111-111-1111
//Initialize the first client.
fscanf(fPtr, "%d%s%s%s", &clientId, clientName, clientEmail, clientPhone);
//While not end of the file, initialize rest of the clients.
while(!feof(fPtr)){
//Have not yet implemented.
}
fclose(fPtr);
}
}
如何将第一个客户端值初始化为
clientId = 1111
clientName[30] = Name One
clientEmail[30] = Email.email.1
clientPhone[30] = 111-111-1111
这里有一个解决方案,不使用scanf
,而是使用getline
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
typedef struct Client_s
{
int clientId;
char clientName[30];
char clientEmail[30];
char clientPhone[30];
} Client;
Client* get_next_client(FILE *f_ptr)
{
Client *new_client = malloc(sizeof(Client));
char *buff = malloc(30);
size_t size = 30;
int error = 0;
if (new_client == NULL || buff == NULL)
return NULL;
if (getline(&buff, &size, f_ptr) <= 0)
return NULL;
new_client->clientId = atoi(buff);
if (getline(&buff, &size, f_ptr) <= 0)
return NULL;
strncpy(new_client->clientName, buff, strlen(buff) - 1);
if (getline(&buff, &size, f_ptr) <= 0)
return NULL;
strncpy(new_client->clientEmail, buff, strlen(buff) - 1);
if (getline(&buff, &size, f_ptr) <= 0)
return NULL;
strncpy(new_client->clientPhone, buff, strlen(buff) - 1);
free(buff);
return new_client;
}
int main(int ac, char **av)
{
FILE * f_ptr = fopen("Client.txt", "r");
if (f_ptr == NULL)
{
write(2, "Could not open filen", strlen("Could not open filen"));
return 1;
}
Client *client = get_next_client(f_ptr);
while (client != NULL)
{
printf("%dn", client->clientId);
//handle client
client = get_next_client(f_ptr);
}
fclose(f_ptr);
return 0;
}
当你不再需要接收到的客户端时,不要忘记释放它们。
希望这能解决你的问题。