Okay. I have a file called "Graduates.txt" in my home directory.
I have a portable program to find the home directory, and I opened the file for reading.
Data in the file looks something like this:
year,firstName,lastName
I need to get this data from this file, and separate it into my struct:
typedef struct alumnus {
int yearGraduated;
char firstName[30];
char lastName[30];
} Alumns;
I have a thought that may or may not work:
A while loop reads through the file, using fgets() to get the data. It then copies it to the struct... but I don't know how to implement any of this.
Sorry if this sounds like dumb question, it most likely is.
#include <stdio.h>
typedef struct alumnus {
int yearGraduated;
char firstName[30];
char lastName[30];
}Alumns;
int main(void) {
Alumns REC1;
FILE *fptr;
fptr = fopen("Test.txt", "r");
fscanf(fptr, "%d,%s,%s", &REC1.yearGraduated, REC1.firstName, REC1.lastName);
printf("%d, %s, %s", REC1.yearGraduated, REC1.firstName, REC1.lastName);
}
Implemented using dasblinkenlight hint.
- Use fgets to read a line from file
- Use String Tokenization to separate the individual elements
Use strtok() for the same.
e.g
FILE *fp;
fp = fopen("path", "r");
char string[150];
char *token;
while(!feof(fp)) {
if (fgets(string,150,fp)) {
printf("%s\n", string);
token=strtok(string,",");
/*Store this token in your struct(your first element) */
}
}
3.Remember strtok() is non-reentrant function,so store the results returned from evey function call of strtok();
Here is a quick example of reading input, using fopen()
, fgets()
and strtok()
and how to format output using correct format strings: (output shown here)
Edited to show placing values into struct Alums
#include <ansi_c.h>
typedef struct alumnus { //Note "alumnus" is not necessary here, you have Alumns
int yearGraduated; //below that will satisfy naming the typedef struct
char firstName[30];
char lastName[30];
}Alumns;
Alumns a, *pA; //Create copy of struct Alumns to use
#define FILE_LOC "C:\\dev\\play\\file10.txt"
int main(void)
{
FILE *fp;
char *tok;
char input[80];
pA = &a; //initialize struct
fp = fopen(FILE_LOC, "r"); //open file (used #define, change path for your file)
fgets(input, 80, fp);
tok = strtok(input, ", \n"); //You can also call strtok in loop if number of items unknown
pA->yearGraduated= atoi(input); //convert this string in to integer
tok = strtok(NULL, ", \n");
strcpy(pA->firstName, tok); //copy next two strings into name variables
tok = strtok(NULL, ", \n");
strcpy(pA->lastName, tok);
//note the format strings here for int, and char *
printf("age:%d\n First Name: %s\n Last Name: %s\n",
pA->yearGraduated, pA->firstName, pA->lastName);
getchar(); //used so I can see output
fclose(fp);
return 0;
}