Hello everybody I have a problem here. I am writing a C Code for reading from a txt file and creating an Index Table from the informations inside this txt. I am reading txt file with getchar() function and taking every char one by one in my "ch" variable. When I am running my program, I am taking the segmantation fault error on the terminal. Here is the all code and I commented the code lines where I am thinking the problem in and which is associated with my question:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{ // Here is my structure of Index Table
char name[10]; // Here is my char array for storing the name data from file
int key;
} fileIndex;
int main(int argc, char *argv[])
{
int i, k=0, j=0, lines=0, offset=0;
char ch;
FILE *pFile;
pFile= fopen("/etc/passwd","r");
if (pFile == NULL)
{
fprintf(stderr, "Failed to open file.\n");
exit(1);
}
while(!feof(pFile))
{
ch = fgetc(pFile);
if(ch == '\n')
{
lines++;
}
}
fileIndex *index = (fileIndex *)malloc(lines);
rewind(pFile);
index[0].key=0;
while(!feof(pFile))
{
ch = fgetc(pFile);
offset++;
if(ch == '\n'){
k++;
index[k].key=offset;}
if(offset==index[k].key+1){// And here I want to take the name information from my txt file
while(ch!=':'){
index[k].name[j]=ch;// Here I am assinging char values one by one to my char array's corresponding index.
j++;
}
}
}
}
Can you help me to fix it please, I tried everything before putting this here. Thank you..