你好我想基于文本文件动态初始化一个数组,但由于某种原因,我做错了。我在第34行" malloc"那个" texto"没有被初始化。
char nome[] = "partidas.txt";
f = fopen(nome, "rt");
int size = fsize(f);
char **texto;
**texto = (char)malloc(size);
int i = 0;
while ((fgets(texto[i], sizeof(texto), f) != NULL))
{
printf("%s\n", texto[i++]);
}
答案 0 :(得分:0)
//remember to include the right header files
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define READ_LENGTH 1024
char* pFileContents = NULL;
int iContentsIndex = 0;
long int sz = 0;
FILE* pFD = NULL;
int readCount = 0;
int stat = 0;
// note: all errors are printed on stderr, success is printed on stdout
// to find the size of the file:
// You need to seek to the end of the file and then ask for the position:
pFD = fopen( "filename", "rt" );
if( NULL == pFD )
{
perror( "\nfopen file for read: %s", strerror(errno) );
exit(1);
}
stat = fseek(pFD, 0L, SEEK_END);
if( 0 != stat )
{
perror( "\nfseek to end of file: %s", strerror(errno) );
exit(2);
}
sz = ftell(pFD);
// You can then seek back to the beginning
// in preparation for reading the file contents:
stat = fseek(pFD, 0L, SEEK_SET);
if( 0 != stat )
{
perror( "\nfseek to start of file: %s", strerror(errno) );
exit(2);
}
// Now that we have the size of the file we can allocate the needed memory
// this is a potential problem as there is only so much heap memory
// and a file can be most any size:
pFileContents = malloc( sz );
if( NULL == pFileContents )
{
// handle this error and exit
perror( "\nmalloc failed: %s", strerror(errno) );
exit(3);
}
// then you can perform the read loop
// note, the following reads directly into the malloc'd area
while( READ_LENGTH ==
( readCount = fread( pFileContents[iContentsIndex], READ_LENGTH, 1, pFD) )
)
{
iContentsIndex += readCount;
readCount = 0;
}
if( (iContentsIndex+readCount) != sz )
{
perror( "\nfread: end of file or read error", strerror(errno) );
free( pFileContents );
exit(4);
}
printf( "\nfile read successful\n" );
free( pFileContents );
return(0);