我遇到一个问题,我必须将由 264064 个字组成的文本文件读入缓冲区,然后在单独的数组中创建一个字指针数组。我不知道如何创建指向缓冲区中不同数量字符的字指针数组。关于如何解决这个问题有任何提示吗?
#include <stdlib.h>
#include <string.h>
int main()
{
int i,wordCount=0;
long bufsize;
char ch;
//Open File and get number of lines in file
FILE *fp = fopen("words2.txt", "r");
if (fp == NULL) {
printf("Error!");
exit(1);
}
do {
ch = fgetc(fp);
if (ch == '\n')
{
wordCount++;
}
} while (ch != EOF);
fclose(fp);
printf("%d\n",wordCount);
//Reading Words into buffer rawtext
char *rawtext;
fp = fopen("words2.txt", "rb");
if (fp != NULL)
{
if (fseek(fp, 0L, SEEK_END) == 0) {
bufsize = ftell(fp);
if (bufsize == -1) {
exit(1);
}
rawtext = malloc(sizeof(char) * (bufsize + 1));
if (fseek(fp, 0L, SEEK_SET) != 0) { exit(1); }
size_t newLen = fread(rawtext, sizeof(char), bufsize, fp);
if (ferror(fp) != 0) {
fputs("Error reading file", stderr);
} else {
rawtext[newLen++] = '\0';
}
}
//Print out buffer
printf("%s",rawtext);
fclose(fp);
free(rawtext);//Free allocated memory
char *ptr[wordCount];//Array for word-pointers
}
}
最佳答案
如果您保留rawtext
(即不释放它),您可以使用strchr('\n')
来遍历内容,存储到数组中当前位置,检测每个新行字符,在此新行字符处终止字符串,然后继续。因此,您的 ptr 数组将指向末尾的 rawtext 内的每个单词(这就是为什么您不应该释放 rawtext,因为指针然后将指向无效内存):
以下代码应该可以工作:
char* currWord = rawtext;
int nrOfWords = 0;
char* newlinePos;
while ((newlinePos = strchr(currWord,'\n')) != NULL) {
*newlinePos = '\0';
ptr[nrOfWords++] = currWord;
currWord = newlinePos + 1;
}
if (*currWord) {
ptr[nrOfWords++] = currWord;
}
旁注:表达式 char *ptr[wordCount]
可能会将指针数组放在堆栈上,堆栈空间有限,至少小于堆。如果您的文件包含很多单词,这可能会出现问题。使用 char *ptr = malloc((wordCount+1) * sizeof(char*)) 来保留堆上的内存。另请注意 wordCount 后面的 +1
,以防最后一个单词不以新行结束。
关于c - 在c中生成字指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42753993/