我正在用 C 编写一个程序,该程序处理一个文本文件并跟踪每个唯一的单词(通过使用一个具有该单词的 char 数组和其出现次数的计数的结构)并将该结构存储到数据结构中。然而,作业中包含这样的内容:“整个 txt 文件可能非常大,无法保存在主内存中。请在程序中考虑到这一点。”
课后我问他,他说一次读取 X 行文本文件(我想他的建议是 20,000 行?),分析它们并更新结构,直到到达文件末尾。
谁能帮助解释执行此操作的最佳方法并告诉我要使用哪些功能?我对 C 非常非常陌生。
(我当前的程序对于小文件来说是准确且正确的,我只需要使其能够容纳巨大的文件)。
太感谢了!!
EDIT:
fp = fopen(argv[w], "r");
if ((fp) == NULL){
fprintf( stderr, "Input file %s cannot be opened.\n", argv[w] );
return 2;
}
/* other parts of my program here */
char s[MaxWordSize];
while (fscanf(fp,"%s",s) != EOF){
nonAlphabeticDelete(s); // removes non letter characters
toLowerCase(s); //converts the string to lowercase
//attempts to add to data structure
pthread_mutex_lock(&lock);
add(words, &q, s);
pthread_mutex_unlock(&lock);
}
这可行,我只需要调整它以一次浏览文本文件 X 行。
getline() 怎么样?
这是手册页中的示例http://man7.org/linux/man-pages/man3/getline.3.html
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t read;
stream = fopen("/etc/motd", "r");
if (stream == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, stream)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)