C时的读数与无界字大小空格分隔的文本文件 [英] C reading a text file separated by spaces with unbounded word size

查看:98
本文介绍了C时的读数与无界字大小空格分隔的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含由空格分隔的字(串)的文本文件。字符串大小没有限定,也不是字的数目。
我需要做的就是把所有的单词从文件列表中。 (假设列表中正常工作)。
我无法弄清楚如何克服无限字的大小问题。我曾尝试这样的:

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.

有人能帮帮我吗?

Can someone please help me?

推荐答案

考虑从上面提意见建议,这只要没有足够的,或明显刚好够重新分配内存。

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\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时的读数与无界字大小空格分隔的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆