Unique function to read different streams
I'm looking for a way to read file and stdin stream using a unique void
function in C. I'm trying to use this function:
#define ENTER 10 //'\n' ASCII code
........
void read(FILE *stream, char *string) {
char c;
int counter = 0;
do {
c = fgetc(stream);
string = realloc(string, (counter+1) * sizeof(char));
string[counter++] = c;
} while(c != ENTER && !feof(stream));
string[counter-1] = '\0';
}
but it's working only with stdin stream. When I'm using a text file, the
file content isn't visible outside the function. I'm calling this function
like:
read(stdin, inputString);
read(inputFile, fileContent);
and only works right in the first case.
P.S.: Initially, inputString an fileContent have been declared as
char *inputString = malloc(sizeof(char));
char *fileContent = malloc(sizeof(char));
and I know fgetc returns int, the char by char reallocation are expensive
(but I need to use only the necessary memory) and EOF or '\n' are stored
in string (but are replaced by 0-terminator after).
No comments:
Post a Comment