this is More advance exmaple :
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX2 100
struct s
{
char* id; //array of structures Maximum of Five students,
};
int main(int argc,char *argv[])
{
struct s MyArray[5];
FILE *fp;
char *r = NULL;
char d[2];
int n,j,k,m,l;
int i=0;// counters
int u=0;
char line[MAX2];
if ((fp = fopen(argv[1],"r")) == NULL){
printf("cannot open the file that you specified\nThe file has to be in the same directory\n");
exit(1);}
d[0] = ':';
d[1] = '\0';
i = 0;
while((fgets(line,100,fp)) != NULL )
{
n=0;
for(k = 0; k < 100; k++){
if (line[k] == '\n'){
line[k] = '\0';
break;
}
}
r = strtok(line,d);
MyArray[i].id = r;
n = strlen(r);
MyArray[i].id[n] = '\0';
++i;
}
printf("%s\n",MyArray[0].id);
fclose(fp);
return 0;
}
the file-input
Code:
s1:csc212,csc281,csc361
s2:csc361,csc336,csc329
s3:csc336,csc327,csc212,csc281
s4:csc342,csc327,csc311,csc305
s5:csc212,csc281,csc327,csc380
output of the program:
why every element in the array print s5 , i think it should print s1 ???