C 读取由空格分隔的文本文件,字大小不受限制 [英] C reading a text file separated by spaces with unbounded word size
问题描述
我有一个文本文件,其中包含以空格分隔的单词(字符串).字符串的大小没有限制,单词的数量也没有限制.我需要做的是将文件中的所有单词放在一个列表中.(假设列表工作正常).我不知道如何克服无界字长问题.我试过这个:
I have a text file that contains words (strings) that are separated by spaces. The strings' size aren't bounded, nor is the number of words. What I need to do is to put all the words from the file in a list. (Assume the list works fine). I cannot figure out how to overcome the unbounded word size problem. I have tried this :
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();
我的文本文件如下所示:
My text file looks like this:
this is sparta
请注意,我所能得到的只是第一个词,甚至我做错了,因为我得到了错误:
Notice that that all I was able to get was the first word, and even that I do improperly because I get the error:
Access violation writing location 0x00B36860.
有人可以帮我吗?
推荐答案
根据上述评论者的建议,这会在内存不足或显然足够时重新分配内存.
Taking suggestions from commenters above, this reallocates memory whenever there is not enough, or apparently just enough.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fatal(char *msg) {
printf("%s
", 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 **
", (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
", 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 读取由空格分隔的文本文件,字大小不受限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!