>but if someone have a better solution welcome
Read can be made to be more efficient, but I'm sure you can figure that one out without too much trouble. Hint: Remove malloc and free for every line, but still allow for variable length strings.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void Write ( const char *string, FILE *fp );
void Read ( FILE *fp );
int main ( void )
{
FILE *fp;
fp = fopen ( "input.txt", "w+b" );
if ( fp == NULL ) {
perror ( NULL );
return EXIT_FAILURE;
}
Write ( "this is a test", fp );
Write ( "another test", fp );
Write ( "different length strings", fp );
rewind ( fp );
Read ( fp );
fclose ( fp );
return EXIT_SUCCESS;
}
void Write ( const char *string, FILE *fp )
{
size_t len;
assert ( string != NULL );
assert ( fp != NULL );
len = strlen ( string ) + 1;
fwrite ( &len, sizeof len, 1, fp );
fwrite ( string, len, 1, fp );
}
void Read ( FILE *fp )
{
size_t len;
assert ( fp != NULL );
while ( fread ( &len, sizeof len, 1, fp ) == 1 ) {
char *string = malloc ( len );
if ( string == NULL ) {
fprintf ( stderr, "Fatal error\n" );
return;
}
fread ( string, len, 1, fp );
puts ( string );
free ( string );
}
}
>So simply ignore cout and imagine that there are printf and gets
We would still call you on it. gets is a Bad Thing most of the time. fgets should be used instead.