Я хочу прочитать содержимое текстового файла в массиве char в C. Должны быть сохранены новые строки.
Как это сделать? Я нашел некоторые С++-решения в Интернете, но не C-решение.
Изменить: теперь у меня есть следующий код:
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;
}
Я получаю одно предупреждение: предупреждение: присваивание делает указатель из целого без трансляции. Это находится на линии size = (int)lSize;
. Если я запустил приложение, оно будет segfaults.
Обновление: приведенный выше код работает. Я нашел segfault, и я задал еще один вопрос. Спасибо за помощь.