我正在用 C 语言编写一个程序,它处理一个文本文件并跟踪每个唯一的单词(通过使用一个包含单词的 char 数组及其出现次数的结构)并将该结构存储到一个数据结构。但是,作业中包含以下内容:“整个 txt 文件可能非常大,无法保存在主内存中。在您的程序中考虑到这一点。”
课后我问他,他说一次读X行文本文件(我想他的建议是20,000行?)一次,分析它们并更新结构,直到你读完的文件。
任何人都可以帮助解释执行此操作的最佳方法并告诉我使用哪些功能?我对 C 非常非常陌生。
(我当前的程序对于小文件是准确无误的,我只需要让它适应大文件)。
非常感谢!!
编辑:
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);
}
关于c - 如何按行 block 处理 C 中的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34081158/