-3

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;
    }
santostiagoo
  • 1
  • 1
  • 2
  • 1
    Are you taking the same class as [Madmartigan](http://stackoverflow.com/questions/23497362)? ;-) – DevSolar May 06 '14 at 15:03
  • 1
    @Madmartigan helped with the other question... The link that you post is to another question that I put here but. It's similar but it's different. The other case is with a single char and this one is with a word... – santostiagoo May 06 '14 at 15:07
  • @santostiagoo: Sorry, misread by me - the other question was *answered* by Madmartigan, not asked by him. – DevSolar May 06 '14 at 15:15

1 Answers1

0
#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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • @ryyker Yes. Sorry if it sounds harsh, but I do think those reasons are important! – anatolyg May 06 '14 at 16:21
  • Of course, it can not be guaranteed to be the fastest. However, it seems to be fast enough. It may be improved by reducing the I-O to the file. But it may be slow, as opposed to when the file is small. – BLUEPIXY May 06 '14 at 16:27
  • @anatolyg - did you _really_ down vote for those reasons? How can you request that anyone anticipate _future requirements_? That is not even reasonable. Nor is _your_ requirement of what comments a person leaves, i.e. if they do not comment _that code may not be fast enough_ you are going to go around and down vote. How is that helping anyone? – ryyker May 06 '14 at 16:29