I have text file and I want to save each line to array of strings (global defined as fileA). All I know is that all rows in file are shorter then 101 characters. I made 3 functions:
char * lineToString(char * filename, int line)- return value of selected lineint getLineCount(char * filename)- return number of lines in file (counting form 1)char * fileToArray(char * filename)- return array of strings
I think this functions work as they should, problem is somewhere in main(). I had printed sizeof(...) just for debugging. Also there is many warnings in my code, how can I fix them?
Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int MAX_LINES = 1000; //0 <= x && x < 1000
int MAX_ROW_LENGTH = 101; //100 + 1 ('\0')
char * fileA = NULL;
char * lineToString(char * filename, int line){
FILE * file = fopen(filename, "r");
int currLine = 1;
int currCol = 0;
char currChar;
char * string = (char *) malloc(sizeof(char)*MAX_ROW_LENGTH);
string[0] = '\0';
if(file != NULL && line >= 1){
while((currChar = getc(file)) != EOF){
if(currLine == line){
if(currChar == '\n'){
string[currCol] = '\0';
break;
}else{
string[currCol] = currChar;
currCol++;
}
}
if(currChar == '\n') currLine++;
}
fclose(file);
}
return string;
}
int getLineCount(char * filename){
FILE * file = fopen(filename, "r");
int count = 0;
char c;
if(file != NULL){
while((c = getc(file)) != EOF)
if(c == '\n') count++;
fclose(file);
}
return count;
}
char * fileToArray(char * filename){
int i;
int lineCount = getLineCount(filename);
char array[lineCount][MAX_ROW_LENGTH];
for(i = 1; i <= lineCount; i++){
strcpy(array[i], lineToString(filename, i));
//printf("%s\n", array[i]);
}
printf("%d\n",sizeof(array));
return array;
}
int main(int argc, char **argv){
fileA = (char *) malloc(sizeof(fileToArray(argv[1])));
strcpy(fileA, fileToArray(argv[1]));
printf("%d\n", (int) sizeof(fileA));
int i;
for(i = 0; i < (int) sizeof(fileA); i++){
printf("%s\n", fileA[i]);
}
return 0;
}
Console:
matjazmav:~/FRI13_14/SE02/P2/DN/DN08$ gcc 63130148-08.c -o 63130148-08
63130148-08.c: In function ‘fileToArray’:
63130148-08.c:58:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat]
63130148-08.c:59:2: warning: return from incompatible pointer type [enabled by default]
63130148-08.c:59:2: warning: function returns address of local variable [enabled by default]
63130148-08.c: In function ‘main’:
63130148-08.c:69:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]
matjazmav:~/FRI13_14/SE02/P2/DN/DN08$ ./63130148-08 input-1a input-1b
808
8
Segmentation fault (core dumped)