我有一个文本文件,其中包含由空格分隔的单词(字符串)。字符串的大小没有限制,单词的数量也没有限制。 我需要做的是将文件中的所有单词放入列表中。 (假设该列表工作正常)。 我不知道如何克服无限字长问题。我已经尝试过这个:
FILE* f1;
f1 = fopen("file1.txt", "rt");
int a = 1;
char c = fgetc(f1);
while (c != ' '){
c = fgetc(f1);
a = a + 1;
}
char * word = " ";
fgets(word, a, f1);
printf("%s", word);
fclose(f1);
getchar();
我的文本文件如下所示:
this is sparta
请注意,我所能得到的只是第一个单词,甚至我做得不正确,因为我收到了错误:
Access violation writing location 0x00B36860.
有人可以帮我吗?
最佳答案
根据上面评论者的建议,只要内存不足或明显足够,就会重新分配内存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fatal(char *msg) {
printf("%s\n", msg);
exit (1);
}
int main() {
FILE* f1 = NULL;
char *word = NULL;
size_t size = 2;
long fpos = 0;
char format [32];
if ((f1 = fopen("file1.txt", "rt")) == NULL) // open file
fatal("Failed to open file");
if ((word = malloc(size)) == NULL) // word memory
fatal("Failed to allocate memory");
sprintf (format, "%%%us", (unsigned)size-1); // format for fscanf
while(fscanf(f1, format, word) == 1) {
while (strlen(word) >= size-1) { // is buffer full?
size *= 2; // double buff size
printf ("** doubling to %u **\n", (unsigned)size);
if ((word = realloc(word, size)) == NULL)
fatal("Failed to reallocate memory");
sprintf (format, "%%%us", (unsigned)size-1);// new format spec
fseek(f1, fpos, SEEK_SET); // re-read the line
if (fscanf(f1, format, word) == 0)
fatal("Failed to re-read file");
}
printf ("%s\n", word);
fpos = ftell(f1); // mark file pos
}
free(word);
fclose(f1);
return(0);
}
程序输入
this is sparta
help 30000000000000000000000000000000000000000
me
程序输出:
** doubling to 4 **
** doubling to 8 **
this
is
sparta
help
** doubling to 16 **
** doubling to 32 **
** doubling to 64 **
30000000000000000000000000000000000000000
me
关于C 读取由空格分隔且字长不受限制的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28254245/