I finally got my program working using C. Can you suggest any improvements to the writing style or programming style that was used in my program?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *in, *out;
char lineIn[80], nameArr1[30], nameArr2[30], roleArr[50], lineOut[1024];
char *namePtr, *rolePtr;
int i, linesRead, linesWrote;
//Open our input file in read mode
if((in=fopen("UsersAndRoles.csv","r")) == NULL)
{
printf("Error opening input file...Exiting!\n");
exit(EXIT_FAILURE);
}
//Open our output file in write mode
if((out=fopen("MergedUsersAndRoles.csv","w")) == NULL)
{
printf("Error creating output file...Exiting!\n");
exit(EXIT_FAILURE);
}
printf("Input and output files are open...\n");
//Initialise our variables
memset(lineIn,0,80);
memset(nameArr1,0,30);
memset(nameArr2,0,30);
memset(roleArr,0,50);
memset(lineOut,0,1024);
namePtr=NULL;
rolePtr=NULL;
i=0;
linesRead=0;
linesWrote=0;
while(!feof(in))
{
//Read a line from the input file
fgets(lineIn,80,in);
//Tokenise the input line into its constituents
namePtr=strtok(lineIn,",");
rolePtr=strtok(NULL,"\r");
if (namePtr != NULL && rolePtr != NULL)
{
//Assign the name to the array nameArr1
for(i=0;*namePtr != '\0';i++)
{
nameArr1[i]=*namePtr;
namePtr++;
} //end for
nameArr1[i]='\0';
//Assign the role to the array roleArr
for(i=0;*rolePtr != '\0';i++)
{
roleArr[i]=*rolePtr;
rolePtr++;
} //end for
roleArr[i]='\0';
//If names are the same, add the role to current line
if(strcmp(nameArr1,nameArr2) == 0)
{
strcat(lineOut,",");
strcat(lineOut,roleArr);
} //end if
//If names are not same print our line and start the new line
else
{
memset(lineOut+strlen(lineOut)+1,'\0',1);
//Checking to ensure that we are compared 2 names and not NULLS
if (linesRead >= 2)
{
//Write out to the file
fputs(lineOut,out);
fputs("\n",out);
linesWrote++;
}
memset(lineOut,0,1024);
strcat(lineOut,nameArr1);
strcat(lineOut,",");
strcat(lineOut,roleArr);
memset(nameArr2,0,30);
memcpy(nameArr2, nameArr1, strlen(nameArr1));
} //end else
} //end if
//Increment the line counter
linesRead++;
} //end while
//Write out the last line to the file
memset(lineOut+strlen(lineOut)+1,'\0',1);
fputs(lineOut,out);
fputs("\n",out);
linesWrote++;
//Close input and output files
fclose(in);
fclose(out);
//Print some statistics
printf("\nTotal number of lines read: %d",--linesRead);
printf("\nTotal number of lines wrote: %d\n",linesWrote);
printf("\nInput and output files are closed...\n");
return (EXIT_SUCCESS);
}