[英]How do I use fscanf to read file to initialize values in C?
假设我有如下所示的 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
客户端 txt 文件包含客户端的 id、名称、email 和电话号码。
现在的任务是从客户端文件中读取并将 id、名称、email 和电话号码保存到名为 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 file\n", strlen("Could not open file\n"));
return 1;
}
Client *client = get_next_client(f_ptr);
while (client != NULL)
{
printf("%d\n", client->clientId);
//handle client
client = get_next_client(f_ptr);
}
fclose(f_ptr);
return 0;
}
当您不再需要接收到的客户时,不要忘记释放它们。
希望能解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.