P
paktsardines
Hi all
I am trying to write a function that reads a file into a dynamically
allocated 2d array of char, something like the following prototype:
char ** read_file(char * filename)
Ideally I would like it to behave like the following perl:
sub read_file {
my $filename=shift(@_)
my @lines;
open(FILE, "<$filename") || die ("Cannot open $filename\n");
@lines=<FILE>;
close(FILE);
return @lines;
}
so far I have something like:
void main(void) {
char ** file_lines = readfile("test.txt");
printf("%s\n",*file_lines[0]);
}
And the function:
char ** read_file(char * filename) {
FILE *fptr;
char *line = malloc(LINE_MAX * sizeof(char));
char **lines = 0;
int linelength = 0;
int i = 0;
// Try to open the file
if ((fptr=fopen(filename,"r"))!=NULL) {
while (fgets(line,LINE_MAX,fptr)!=NULL) {
linelength=strlen(line);
line[linelength]='\0';
if ((lines= realloc(lines, (i *linelength +1) *
sizeof(char *)))==NULL) {
printf("Cannot allocate memory\n");
exit(1);
}
lines=line;
i++;
}
}
else {
printf("Cannot open %s for reading.\n",filename);
exit(1);
}
free (line);
return lines;
}
The program currently seems to get through the function okay, but
then seg faults when printing the first line.
Thanks for any pointers, (boom boom
Pakt.
I am trying to write a function that reads a file into a dynamically
allocated 2d array of char, something like the following prototype:
char ** read_file(char * filename)
Ideally I would like it to behave like the following perl:
sub read_file {
my $filename=shift(@_)
my @lines;
open(FILE, "<$filename") || die ("Cannot open $filename\n");
@lines=<FILE>;
close(FILE);
return @lines;
}
so far I have something like:
void main(void) {
char ** file_lines = readfile("test.txt");
printf("%s\n",*file_lines[0]);
}
And the function:
char ** read_file(char * filename) {
FILE *fptr;
char *line = malloc(LINE_MAX * sizeof(char));
char **lines = 0;
int linelength = 0;
int i = 0;
// Try to open the file
if ((fptr=fopen(filename,"r"))!=NULL) {
while (fgets(line,LINE_MAX,fptr)!=NULL) {
linelength=strlen(line);
line[linelength]='\0';
if ((lines= realloc(lines, (i *linelength +1) *
sizeof(char *)))==NULL) {
printf("Cannot allocate memory\n");
exit(1);
}
lines=line;
i++;
}
}
else {
printf("Cannot open %s for reading.\n",filename);
exit(1);
}
free (line);
return lines;
}
The program currently seems to get through the function okay, but
then seg faults when printing the first line.
Thanks for any pointers, (boom boom
Pakt.