I am trying to get this to work for my assignment but I keep getting a segmentation fault error but I can't see a problem.
struct line{
int source;
int dest;
int type;
int port;
char data[51];
};
int main(){
struct line *dataIn;
dataIn = malloc(sizeof(struct line));
int nRecords = 0;
readFile(&nRecords, dataIn);
int i=0;
for(i = 0; 1 < 100; i++){
printf("Source: %d Data: %s\n", dataIn[i].source, dataIn[i].data);
}
return 0;
}
void readFile(int *nRecords, struct line *dataIn){
FILE *fileIn;
fileIn =fopen("data.txt","r");
if (!fileIn){
puts("File Open Error");
return 1;
}
while(fscanf(fileIn, "%d:%d:%d:%d:%[^\n]", &dataIn[*nRecords].source, &dataIn[*nRecords].dest, &dataIn[*nRecords].type, &dataIn[*nRecords].port, dataIn[*nRecords].data) == 5){
nRecords++;
dataIn = realloc(dataIn,(*nRecords+1)*sizeof(struct line));
}
fclose(fileIn);
}
Also when I add the function prototype at the top:
void readFile(int*, struct line*);
I get the error:
Conflicting Types for 'readFile'
nRecordsbut not using that in the for loop. Why?char data[51]for data? You said you where parsing a "dynamic structure". If your input is > 51 bytes, you will scribble over the stack pointer and be unable to return fromreadFile(). I think you need to do two things. 1. rethink the way you manage memory as this is quite convoluted and will be hard to support. 2. Stop using any form of scanf as it's dangerous.