Here is my code. I was struggling at why strncpy()
cant copy the string into a struct
, since it was works perfectly in my previous assignment. Also, I have second question: suppose I have a struct contains another struct, how to assign the value to the inside struct:
struct _field {
char fieldName[50];
char fieldType[50];
int fieldLength;
};
struct _table {
char *tableFileName;
int reclen;
int fieldcount;
struct _field fields[100];
};
typedef enum { false, true } bool;
bool loadSchema(struct _table *table) {
printf("%s\n", "*** LOG: Loading table fields...");
FILE *fp = NULL;
char lines[1000];
char s[2] = " ";
fp = fopen("in.txt", "r+");
while (fgets(lines, sizeof(lines), fp) != NULL) {
char *token;
token = strtok(lines, s);
if (token != NULL) {
if (strcmp(token, "CREATETABLE") == 0) {
token = strtok(NULL, s);
if (token != NULL) {
token[strlen(token)-1] = '\0';
strcat(token, ".bin");
//table->tableFileName = token; // this line can write the value into struct
strncpy(table->tableFileName, token, 20);// this line cant write the value into struct
}
printf("*** LOG: Table name is [%s]\n", table->tableFileName);
}
/*if (strcmp(token, "ADD") == 0) {
token = strtok(NULL, s);
if (token != NULL) {
strncpy((*table).fields. fieldName, token, 50);
}// Q2: how to give a value into a struct of a struct?
}*/
}
}
return 1;
}
Input file looks like this:
CREATETABLE people
ADD id char 50
ADD lname char 50