Hi,
I have to txt files, and want them to read into an array line by line and after then a split the lines with delimeters, at the first file I use ";\n", at the second file I want to split the lines to single words by spaces. My aim is to get the first word from the first file and compare with all the words from the other file, to check is there any matches.
My problem is, that at the first file works everything fine, and I want to do the with the second file, but after reading the lines into lines_input[], I check the an empty = null line, I get segmentation fault.
Please help me, I don't know what I'm doing wrong.
Thanks for every response!
You can see the code below:
Code:
#include <stdio.h>#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
//Change the \n and \t to \0
void strip(char *s) {
char *p2 = s;
while(*s != '\0') {
if(*s != '\t' && *s != '\n') {
*p2++ = *s++;
} else {
++s;
}
}
*p2 = '\0';
}
char *concat (char * a, char* b)
{
char *c = malloc(strlen(a) + strlen(b) + 1);
if ( b != NULL )
{
if ( c != NULL )
{
strcpy(c, a);
strcat(c, b);
}
}
return c;
}
int main(){
// File read
FILE *dict_f;
dict_f = fopen("fogalom.txt", "r");
// Check
if (dict_f == NULL){ perror("Sikertelen fajlmegnyitas\n"); exit(1); }
char line_f[101];
char *lines_f[15];
char *eof;
//Reading line by line to lines_f[]
int j=0;
while((eof = fgets(line_f, 101, dict_f)) != NULL){
lines_f[j] = strdup(eof);
j++;
}
//fill up the places in the lines_f[] with null
while (j!= 14)
{
lines_f[j] = NULL;
j++;
}
fclose(dict_f);
printf("%s\n", lines_f[0]);
printf("%s\n ", lines_f[1]);
printf("%s\n ", lines_f[9]);
char *tomb[LINES];
char *sor;
int i;
//Splittink
if(lines_f[0] != NULL)
{
sor = strdup(lines_f[0]);
tomb[0] = strtok(sor,";\n");
i = 0;
while(tomb[i]!= NULL)
{
printf("%i. elem: %s\n", i, tomb[i]);
i++;
tomb[i] = strtok(NULL, ";\n");
}
}
//----------NEXT FILE ---------------------------
FILE *input_f;
input_f = fopen("fogalom.txt", "r");
if (input_f == NULL){ perror("Sikertelen fajlmegnyitas:\n"); exit(1); }
char line_input[101];
char *lines_input[15];
j=0;
while((eof = fgets(line_input, 101, input_f)) != NULL){
lines_input[j] = strdup(eof);
j++;
}
while (j!= 14)
{
lines_input[j] = NULL;
j++;
}
fclose(input_f);
return 0;
}