I am attempting to read a file with some random names in the format "ADAM","MARK","JESSIE" .....
I have some constraints, the file should be read in a function but should be accessible form the main function with no global variables. The file size and the no of names in the file are not known. This is what I have done till now. I have some difficulty with dynamic 2d array as I have not used them much.
/* Function to read from the file */
int read_names(FILE *input, char ***names, int *name_count)
{
int f1,size,count,i,j=0;
char **name_array,*text,pos=0;
/* get the file size */
f1=open("names.txt",O_RDONLY);
size=lseek(f1,0,SEEK_END);
close(f1);
/* Reading all the characters of the file into memory */
//Since file size is known we can use block transfer
text=(char *) malloc(size * sizeof(char) );
fscanf(input,"%s",text);
/* Finding the no of names in the file */
for(i=0;i<size;i++)
{
if(text[i]==',')
count++;
}
printf("No. of names determined\n");
/* Assigning the Name count to the pointer */
name_count=(int*)malloc(sizeof(int));
*name_count=count;
name_array=(char **) malloc(count * sizeof(char *));
for(i=0;i<count;i++)
{
name_array[i]=(char*) malloc(10 *sizeof(char ));
}
for(i=0;i<size;i++)
{
if(text[i]!='"')
if(text[i]==',')
{
**name_array[pos][j]='\0'; //error here
pos++;
j=0;
}
else
name_array[pos][j++]=text[i];
}
printf("Names Counted\n");
printf("Total no of names: %d\n",*name_count);
names=(char ***) malloc(sizeof(char **);
names=&name_array;
return 1;
}
/* Main Function */
int main(int argc, char *argv[])
{
FILE *fp;
char ***names;
int *name_count;
int status;
// Opening the file
fp = fopen("names.txt","r");
// Now read from file
status = read_names(fp,names,name_count);
printf("From Main\n");
fclose(fp);
system("PAUSE");
return 0;
}
I use WxDev and am getting an error "invalid type argument of `unary *' when I try to assign the null character.
Any pointers on how to do this?