Suppose I have Client.txt file that looks like this. Client.txt file picture
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
The Client txt file contains client's id, name, email, and phone number.
Now the task is to read from the Client file and save id, name, email, and phone number into a struct called Client. From this Client text file, I will make three struct values which are going to be pushed in to a list of structs.
But since I am just learning how to use fscanf, and in an attempt practice fscanf, I am narrowing the task into: how to read from text and initialize the first client's values?
Here is what I attempted.
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);
}
}
How can I initialize the first client value as
clientId = 1111
clientName[30] = Name One
clientEmail[30] = Email.email.1
clientPhone[30] = 111-111-1111
Here is a solution, not using scanf
but 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;
}
Don't forget to free the recieved Clients when you don't need them anymore.
Hope if fixes your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.