可能最有效的方法是在一个块中将整个文件读入内存(使用fread)。然后分配一个指针数组,每个字一个。然后遍历内存中的文件,将 \n 字符更改为 \0 并将指针存储在数组中每个 \0 之后的字符。
它是高效的,因为它只执行一次 I/O 操作,两次内存分配,并循环文件中的字符两次(一次将它们复制到缓冲区,再一次将它们分解为单独的字符串)。您描述的算法(fscanf 和strcpy)将执行许多 I/O 操作,为每个单词分配内存,并循环字符至少 3 次(一次读入缓冲区,一次查找长度分配内存,并从缓冲区复制一次到分配的内存中)。
这是一个没有错误检查的简单版本:
char* buffer; // pointer to memory that will store the file
char** words; // pointer to memory that will store the word pointers
// pass in FILE, length of file, and number of words
void readfile(FILE *file, int len, int wordcnt)
{
// allocate memory for the whole file
buffer = (char*) malloc(sizeof(char) * len);
// read in the file as a single block
fread(buffer, 1, size, file);
// allocate memory for the word list
words = (char**) malloc(sizeof(char*) * wordcnt);
int found = 1, // flag indicating if we found a word
// (starts at 1 because the file begins with a word)
curword = 0; // index of current word in the word list
// create a pointer to the beginning of the buffer
// and advance it until we hit the end of the buffer
for (char* ptr = buffer; ptr < buffer + len; ptr++)
{
// if ptr points to the beginning of a word, add it to our list
if (found)
words[curword++] = ptr;
// see if the current char in the buffer is a newline
found = *ptr == '\n';
// if we just found a newline, convert it to a NUL
if (found)
*ptr = '\0';
}
}
这是使用strtok 的稍微简单的版本:
char* buffer;
char** words;
void readfile(FILE *file, int len, int wordcnt)
{
buffer = (char*) malloc(sizeof(char) * len);
fread(buffer, 1, size, file);
buffer[len] = '\0';
words = (char**) malloc(sizeof(char*) * wordcnt);
int curword = 0;
char* ptr = strtok(buffer, "\n");
while (ptr != NULL)
{
words[curword++] = ptr;
ptr = strtok(NULL, "\n");
}
}
请注意,以上两个示例假设文件中的最后一个单词以换行符结尾!