Lendo o arquivo de texto inteiro em uma matriz de caracteres em C
Eu quero ler o conteúdo de um arquivo de texto em uma matriz de caracteres em C. Novas linhas devem ser mantidas.
Como eu faço isso? Encontrei algumas soluções C ++ na Web, mas nenhuma solução C somente.
Editar: Eu tenho o seguinte código agora:
void *loadfile(char *file, int *size)
{
FILE *fp;
long lSize;
char *buffer;
fp = fopen ( file , "rb" );
if( !fp ) perror(file),exit(1);
fseek( fp , 0L , SEEK_END);
lSize = ftell( fp );
rewind( fp );
/* allocate memory for entire content */
buffer = calloc( 1, lSize+1 );
if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);
/* copy the file into the buffer */
if( 1!=fread( buffer , lSize, 1 , fp) )
fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);
/* do your work here, buffer is a string contains the whole text */
size = (int *)lSize;
fclose(fp);
return buffer;
}
Recebo um aviso: warning: assignment faz o ponteiro do número inteiro sem uma conversão. Isso está na linhasize = (int)lSize;
. Se eu executar o aplicativo, ele segfaults.
Atualizar: O código acima funciona agora. Eu localizei o segfault e postei outra pergunta. Obrigado pela ajuda.