I am trying to store each value of a column from a text file into an dynamically allocated array, which needs to be globally declared for further usage in the program.
The input textfile contains the following: 34932\t13854\t13854\t2012-01-07\r 172098\t49418\t53269\t2012-01-07\r
I have written the following code:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *int_file1;
int BUF = 1024;
char first_col[BUF],sec_col[BUF],third_col[BUF],fourth_col[BUF];
int index=0,i=0;
char *array1=malloc(10*sizeof(char));
int_file1=fopen("test.txt","r");
if(int_file1 == NULL)
{
perror("Error while opening the file.\n");
}
else
{
while(fscanf(int_file1,"%[^\t]\t%[^\t]\t%[^\t]\t%[^\n]",first_col,sec_col,third_col,fourth_col) == 4)
{
// printf("%s",first_col);
array1=realloc(array1,strlen(first_col)+1);
array1[index]=first_col;
index++;
}
}
fclose(int_file1);
printf("%s",array1[1]);
return 0;
}
The commented printf line gives the entire values of the column, which proves that the file is correctly being read.
But on compiling this program I get both compiler warnings and finally segmentation fault.
Please suggest where I am getting it wrong.