Hey there~ Im having some problem with file reading and writing...Im suppose to read an external file which have comma seperated values..So I'm suppose to seperate each part (and store it as Name, Race, Class, Lvl, Guild) and store it in a structure. But there's some problem..Here's my code:
Code:
/* Header files. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Constants */
#define MAXSIZE 70
#define NAME_LEN 12
#define RACE_LEN 20
#define CLASS_LEN 7
#define GUILD_LEN 30
typedef struct recordStruct
{
char name[NAME_LEN];
char race[RACE_LEN];
char class[CLASS_LEN];
char lvl;
char guild[GUILD_LEN];
} Record;
/* Main Program which takes in arguments from Unix*/
int main(int argc, char *argv[])
{
/* Variable Declarations */
Record *record;
FILE *in, *out;
char *rec, *field;
int field_num;
in = fopen(argv[1], "r");
out = fopen(argv[2], "wb");
/* Allocates Memory */
rec = malloc(MAXSIZE * sizeof(char));
record = malloc(sizeof(Record));
field = malloc(MAXSIZE * sizeof(char));
while(fgets(rec, MAXSIZE, in) != NULL)
{
field = strtok(rec, ",");
field_num = 1;
while(field != NULL)
{
switch(field_num)
{
case 1:
strcpy(record->name,field);break;
case 2:
strcpy(record->race,field);break;
case 3:
strcpy(record->class,field);break;
case 4:
record->lvl = atoi(field);break;
case 5:
strcpy(record->guild,field);break;
}
field = strtok(NULL,",");
field_num++;
}
printf("%s,%s,%s,%d,%s\n",record->name, record->race, record->class, record->lvl,record->guild);
fwrite(record,sizeof(Record),1,out);
}
/* Free allocated memory */
free(rec);
free(field);
/* Close File */
fclose(in);
fclose(out);
return EXIT_SUCCESS;
}
Here's my external file: (there may be 4 or 5 fields in each line meaning the last can be a null value)
Code:
Aoere,Afternoon Elf,Mage,3,
Mosrdbrann,Mailing List Troll,Priest,29,Fiery Legion
Irwumory,Evening Elf,Druid,7,The Forgivers
Schakdynle,Afternoon Elf,Priest,47,Blessed Warriors
Uathakil,Evening Elf,Paladin,50,Online Fighters
Iazhath,Newsgroup Troll,Druid,57,
Btw I'm supposed to store Lvl in one byte only so I'm using char. Anyway i got some funny output..In my printf part it is suppose to display the same output as my external file but this is the output i get:
Code:
Aoere,Afternoon Elf,Mage,3,
Mosrdbrann,Mailing List Troll,Priest,29,Fiery Legion
Irwumory,Evening Elf,Druid,7,The Forgivers
Schakdynle,Afternoon Elf,Priest,47,Blessed Warriors
Uathakil,Evening Elf,Paladin2OnlineFighters,50,Online Fighters --> this line!
Iazhath,Newsgroup Troll,Druid,57,Online Fighters --> and this line!
It's really long but..I hope someone can help me out with this! Hope i have provided sufficient information! Thanks a lot!!!!