0
I have an inputstream header. h that defines a struct having a string, an int and a readc Function. In this header I define the Function init receiving as parameter a string having the absolute directory of a file, and the struct inputstream, in this file I read the file and pass the data to the source variable of inputstream. Here comes the code:
inputstream. h
#ifndef INPUTSTREAM_H
#define INPUTSTREAM_H
#include <stdio.h>
typedef struct
{
char *source; // header source code
int pos;
char (*readc)();
}inputstream;
void init(const char*, inputstream*);
#endif
inputstream. c
#include "inputstream.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
inputstream *is;
char readc()
{
return is->source[is->pos++];
}
void init(const char *file_header, inputstream *stream)
{
memset(stream, 0, sizeof(inputstream));
stream->readc = &readc;
FILE *header = fopen(file_header, "r");
if (header == NULL)
{
printf("Cannot open file\nExiting...\n");
exit(EXIT_FAILURE);
}
fseek(header, 0, SEEK_END);
long lenght = ftell(header);
if (lenght <= 0)
{
printf("Empty file\nExiting...\n");
exit(EXIT_FAILURE);
}
fseek(header, 0, SEEK_SET);
stream->source = (char*) malloc(lenght + 2);
//memset(stream->source, 0, sizeof stream->source);
fread(stream->source, lenght + 1, 1, file_header);
fclose(header);
}
When running Function init the error of Segmentation fault occurs. I have debugged and it seems that the problem is in Function fread. What’s wrong with the code?
Attention to typographical error of
lenght
that should belength
and is very common in our language. How is calling the function in themain
?– Isac
init("/home/file.txt", &is);
– Carlos Henrique