i guess i should rephrase my question. i have a structure like below:
struct profile {
char name[30];
int age, phoneNo;
};
i have a file with strings that look like this:
James Brown,35y,0123456789
Mary Brown,45y,0123987456
currently i've written a code to search for a record using the person's name/age/phoneNo, and i'd like to store the records into the struct i have. i'm trying to use strtok
to separate the data from the comma, but my code is not working.
int main()
{
char search[50];
char record[50];
const char s[2] = ",";
char* token;
struct profile c;
FILE* fPtr;
if (fPtr = fopen("profile.txt", "r"))
{
// flag to check whether record found or not
int foundRecord = 0;
printf("Enter name to search : ");
// fgets gets name to search
fgets(search, 50, stdin);
//remove the '\n' at the end of string
search[strcspn(search, "\n")] = 0;
while (fgets(record, 50, fPtr))
{
// strstr returns start address of substring in case if present
if (strstr(record, search))
{
token = strtok(record, s);
while (strtok != NULL)
{
scanf("%s", c.name);
token = strtok(record, s);
scanf("%d", c.age);
token = strtok(record, s);
scanf("%d", c.phoneNo);
token = strtok(NULL, s);
printf("Your details: ");
printf("%s, %d, %d\n", c.name, c.age, c.phoneNo);
}
foundRecord = 1;
}
}
if (!foundRecord)
printf("%s cannot be found\n", search);
fclose(fPtr);
}
else
{
printf("File cannot be opened\n");
}
}
i've never used strtok
before and i'm not sure how to store each token into each struct variables. could someone explain to me how i can fix the strtok
function in my code?
As advised in comments, you can easily read a comma delimited string using strtok
. You can use atoi
/sscanf
to extract integer value from age. I modified your code a little to read from file to assign to struct array:
// Array for storing Profiles
struct profile profiles[2];
FILE* fPtr;
if (fPtr = fopen("profile.txt", "r")) {
int index = 0;
while (fgets(record, 50, fPtr) != NULL) {
// Extract name
char *pStr = strtok(record, ",");
if (pStr != NULL) {
strcpy(profiles[index].name, pStr);
}
// Extract Age
pStr = strtok(NULL, ",");
if (pStr != NULL) {
profiles[index].age = atoi(pStr);
}
// Extract Phone No
pStr = strtok(NULL, ",");
if (pStr != NULL) {
profiles[index].phoneNo = atoi(pStr);
}
index++;
}
for (int i = 0; i < 2; i++) {
printf("%s %d %d\n", profiles[i].name, profiles[i].age, profiles[i].phoneNo);
}
fclose(fPtr);
}
When I ran this, I was able to see expected output:
src : $ cat profile.txt
James Brown,35y,0123456789
Mary Brown,45y,0123987456
src : $ gcc readfiletostructarr.c
src : $ ./a.out
James Brown 35 123456789
Mary Brown 45 123987456