Problem with text file input
I posted a while back about reading in a sparse matrix but I'm having some real trouble with reading in text input.
My plan in case the file was not standardised was to read in a line at a time, then split that line down into elements based on a set of delimiters (probably "," and "\n")
My program keeps segfaulting and it's driving me mad - I think I know where but not why
All i want to do is is be able to print an element so i know the function is working as intended but it keeps crashing. My ultimate goal will be to have a list of delimiters which i can use like strtok(linebuffer,delims)
int fileopen(char *argv)
FILE *file = fopen( argv, "r" ); //Open textfile with name given as an argument (argv) in read-only mode. fopen returns 0 on failure
if (file == 0)
fprintf(stderr,"Error in opening file: %s \n",argv);
int dimensionRow, dimensionCol;
int row, col, val; // Location and value to populate
int lineno = 0; // lineno in textfile;
char *element = NULL;
while (fgets(linebuffer, sizeof(linebuffer), file) != NULL)
element = strtok(linebuffer, ",");
while (element != NULL )
element = strtok(NULL, ",");
When i run it through gdb it crashed on the print statement.
linebuffer seems to be filled as expected but if i type
i get : $12 = 0xffffffffffffe1c0 <Address 0xffffffffffffe1c0 out of bounds>
then if i type "step" is segfaults. So I think I must not be using strtok correctly but I'm really stuck.
I've literally spent my entire day playing around with file input/output functions and I've read countless guides and snippets of code and I'm sure it's something silly but I'm at my wits end.
Any help would be appreciated. Thanks
P.s. Currently the textfile i'm reading in looks like this as a test: 5,7,23,42,1,2,5,2