Read WORDS (not char) from file without empty lines in C - not duplicated [duplicate]

☆樱花仙子☆ 提交于 2019-12-13 09:54:13

问题


Hi. I need to read several files without empty lines between words.They can have different layouts, such as 1.txt or 2.txt:


1.txt:

treg
hreger
ig
srg
fre
ig
lre
eg

2.txt:

lregreg

igregr

kreggerg

ereherh

tershs

hsehsteh

asreh

treshse

How do i do that ? How can I count the number of words in the fastest way? I just have the following code:

#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);
}

how i implement something like that:

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

回答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;
}


来源:https://stackoverflow.com/questions/23498148/read-words-not-char-from-file-without-empty-lines-in-c-not-duplicated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!