I have a small assignment in C. The teacher has provided us with the following code. I am unable to understand anything after "r = (struct record*) malloc(sizeof(struct record));". I am fairly new to programming. can some one please explain the code to me ? Any help would be great.
void readTextAndWriteBinary(char *fileName)
{
FILE* infile, *outfile;
char buff[255];
char *pch;
struct record* r;
int counter = 0;
infile = fopen(fileName,"r"); /* open text file for reading */
if (infile == 0){
perror("Error opening text file");
return;
}
outfile=fopen("testdata.dat","wb"); /* open binary file for writing */
r = (struct record*) malloc(sizeof(struct record));
/* skip the first line */
fgets(buff, 255, infile);
/* read text file line by line */
while (!feof(infile)){
fgets(buff, 255, infile);
if (strlen(buff) <= 10)
break;
pch = strtok(buff, ",");
(*r).transType = pch[0]; /* transtype */
pch = strtok(0, ",");
strcpy((*r).seriesID, pch); /* seriesID */
pch = strtok(0, ",");
if (counter % 2 == 0)/* productID */
sprintf((*r).productID, "%d", counter);
else
sprintf((*r).productID, "%d", 353625 - counter);
pch = strtok(0, ","); /* skip empty field - flag */
pch = strtok(0, ",");
(*r).month = atoi(pch); /* month */
pch = strtok(0, ","); /* skip empty field - ex */
pch = strtok(0, ",");
(*r).version= atoi(pch); /* version */
pch = strtok(0, ",");
(*r).generation = atoi(pch); /* generation */
pch = strtok(0, ",");
(*r).index1 = pch[0]; /* index1 */
pch = strtok(0, ",");
(*r).index2 = pch[0]; /* index2 */
pch = strtok(0, ",");
(*r).orderPrice= atof(pch); /* orderPrice */
pch = strtok(0, ",");
strcpy((*r).invStart, pch); /* invStart */
pch = strtok(0, ",");
strcpy((*r).invEnd, pch); /* invEnd */
pch = strtok(0, ",");
(*r).orderSize= atoi(pch); /* orderSize */
pch = strtok(0, ",");
(*r).numOrders= atoi(pch); /* numOrders */
pch = strtok(0, ",");
(*r).aggregate= atoi(pch); /* aggregate */
/* write binary data */
fwrite((struct record*)r,sizeof(struct record),1,outfile);
counter++;
}
fclose(infile);
fclose(outfile);
printf("Binary file created.\n");
} /* readTextAndWriteBinary */
MOD EDIT: When posting code...USE CODE TAGS!!!

New Topic/Question
Reply




MultiQuote





|