我正在尝试组合从文件中读取的字符中的单词。问题在于组合字符。我这样做的方式如下:
char *charArr
while( (readChar = fgetc(fp)) != EOF ){
charArr[i] = readChar;
i++;
}
首先,您需要为charArr
缓冲区分配一些内存;如所写,charArr
最初并没有指向任何有意义的地方:
char *charArr = malloc(SOME_INITIAL_SIZE);
其中 SOME_INITIAL_SIZE 足以处理大多数情况。对于那些不够大的时候,您必须使用realloc()
. 这意味着您还必须跟踪缓冲区的当前大小:
size_t currentSize = 0;
size_t i = 0;
char *charArr = malloc(SOME_INITIAL_SIZE);
if (!charArr)
{
/**
* memory allocation failed: for this example we treat it as a fatal
* error and bail completely
*/
exit(0);
}
currentSize = SOME_INITIAL_SIZE;
while ((readchar = fgetc(fp)) != EOF)
{
/**
* Have we filled up the buffer?
*/
if (i == currentSize)
{
/**
* Yes. Double the size of the buffer.
*/
char *tmp = realloc(charArr, currentSize * 2);
if (tmp)
{
charArr = tmp;
currentSize *= 2;
}
else
{
/**
* The realloc call failed; again, we treat this as a fatal error.
* Deallocate what memory we have already allocated and exit
*/
free(charArr);
exit(0);
}
}
charArr[i++] = readchar;
}
如果您将数组视为字符串,请不要忘记添加 0 终止符。
编辑
但是,更大的问题是为什么您认为必须在过滤数据之前将整个文件的内容读入内存?为什么不随时过滤?