【问题标题】:Read WORDS (not char) from file without empty lines in C - not duplicated [duplicate]从 C 中没有空行的文件中读取 WORDS(非字符) - 不重复 [重复]
【发布时间】:2014-05-06 14:55:59
【问题描述】:

嗨。 我需要读取几个单词之间没有空行的文件。它们可以有不同的布局,例如 1.txt 或 2.txt:


1.txt:

treg
hreger
ig
srg
fre
ig
lre
eg

2.txt:

lregreg

igregr

kreggerg

ereherh

tershs

hsehsteh

asreh

treshse

我该怎么做?如何以最快的方式计算单词数? 我只有以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    FILE *fp;
    char palavra[50]="/0";
    char *s;

    fp = fopen("1.txt","r");
    if(fp == NULL){
    puts("Open file failed\n");
    exit(-1);
    }

    while(fscanf(fp,"%s",palavra)!=EOF){
    s=palavra;
        /*do things with s var*/
    }

    fclose(fp);
    exit(0);
}

我是如何实现这样的:

while ((c = fgetc(fp)) != EOF) { 
    if (isspace(c)){ 
        continue;
    }

【问题讨论】:

  • 你和Madmartigan上同一个班吗? ;-)
  • @Madmartigan 帮助解决了另一个问题...您发布的链接是我放在这里的另一个问题。它很相似,但又不同。另一种情况是单个字符,而这个是一个单词......
  • @santostiagoo:对不起,我误读了 - Madmartigan 回答了另一个问题,他没有问。

标签: c file lines words


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

enum status { OUT, IN };

int main(){
    FILE *fp;
    int ch, wc = 0, stat = OUT;

    if(NULL==(fp = fopen("1.txt","r"))){
        fprintf(stderr, "Open file failed\n");
        exit(-1);
    }

    while(EOF!=(ch=fgetc(fp))){
        if(isspace(ch)){
            stat = OUT;
        } else {
            if(stat == OUT){
                stat = IN;
                ++wc;
            }
        }
    }
    fclose(fp);
    printf("number of words is %d.\n", wc);

    return 0;
}

【讨论】:

  • @ryyker 是的。对不起,如果这听起来很苛刻,但我确实认为这些原因很重要!
  • 当然不能保证是最快的。但是,它似乎足够快。可以通过减少对文件的 I-O 来改进它。但与文件较小时相比,它可能会很慢。
  • @anatolyg - 您是否真的出于这些原因投反对票?您如何要求任何人预测未来的需求?这甚至不合理。 你的对一个人留下的内容的要求也不是,即如果他们不评论代码可能不够快,你就会四处走动并投反对票。这对任何人有什么帮助?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2015-12-21
  • 2022-07-02
  • 2015-04-01
  • 1970-01-01
相关资源
最近更新 更多