W
WStoreyII
the following code is supposed to read a whole line upto a new line
char from a file. however it does not work. it is producing weird
results. please help. I had error checking in there for mallocs and
ect, but i removed them to help me debug. thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void freadl ( FILE *stream, char **string ) {
char next = fgetc ( stream );
char *line;
line = (char*) malloc (1*sizeof(char));
while ( next != '\n' ) {
line = (char*) realloc ( line, (strlen(line) + 1) * sizeof(char) );
line [strlen(line)] = next;
next = fgetc (stream );
}
*string = (char*) malloc((strlen(line))*sizeof(char));
strcpy (*string,line);
free(line);
}
int main ( int argc, char *argv[] ) {
FILE *fp;
fp = fopen ( "fread.c", "r" );
char *str;
freadl ( fp , &str );
printf ( "str = %s, with size of %d\n", str, strlen (str) );
int i;
for ( i = 0; i < strlen (str); i++ ){
char now = str;
printf ( "chr = %c, # = %d\n", now,now);
}
}
char from a file. however it does not work. it is producing weird
results. please help. I had error checking in there for mallocs and
ect, but i removed them to help me debug. thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void freadl ( FILE *stream, char **string ) {
char next = fgetc ( stream );
char *line;
line = (char*) malloc (1*sizeof(char));
while ( next != '\n' ) {
line = (char*) realloc ( line, (strlen(line) + 1) * sizeof(char) );
line [strlen(line)] = next;
next = fgetc (stream );
}
*string = (char*) malloc((strlen(line))*sizeof(char));
strcpy (*string,line);
free(line);
}
int main ( int argc, char *argv[] ) {
FILE *fp;
fp = fopen ( "fread.c", "r" );
char *str;
freadl ( fp , &str );
printf ( "str = %s, with size of %d\n", str, strlen (str) );
int i;
for ( i = 0; i < strlen (str); i++ ){
char now = str;
printf ( "chr = %c, # = %d\n", now,now);
}
}