0

This code does not read the full text file.namely,first 30-40 does not read the word. why ?

word source : http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200009/homework10/simple.dict

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

int main()
{
FILE *fp = fopen("simple.txt","r");

char buf[25];

while (!feof(fp))

{
    fscanf(fp,"%s",buf);
    printf(" %s\n ", buf);

}
fclose(fp);
return 0;

}
4
  • 1
    "does not read the word"? Huh? Your code skips the first 30-40 lines of text? Commented Apr 21, 2015 at 14:34
  • 1
    It would be helpful if you included your output. Commented Apr 21, 2015 at 14:35
  • 3
    Source file called "simple.dict", this code attempts to read "simple.txt". Commented Apr 21, 2015 at 14:36
  • Probably, It is beyond the upper limit of the console buffer. try like as a.out | more Commented Apr 21, 2015 at 14:48

2 Answers 2

1

There are some fishy things:

  1. Check that the file open didn't fail before relying on it.
  2. Don't use feof() like that, it's not what it's for and it won't work.
  3. You only reserve room for 25 characters, that's not very long (your longest word seems to be 14 characters though, so it should be fine).
  4. You should check the return value of fscanf() (in fact, that can be used to replace feof()).
Sign up to request clarification or add additional context in comments.

3 Comments

I did 14 characters reserved.This time, the first 30 words read.
@johnalanson Noooo, don't decrease it! 25 is pretty low as is, and you must have room for the string terminator! 14 won't work.
does not unfortunately.
0

you can open file and line-by-line read file context like that

int main() 
{
    /* Used variables */
    FILE *file;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    /* Open file descriptor */
    file = fopen("simple.txt", "r");
    if(file != NULL)
    {

        /* Line-by-line read file */
        while ((read = getline(&line, &len, file)) != -1) 
        {
            /* Print line */
            printf("%s\n", line);
        }

        /* Close file descriptor and free line */
        fclose(file);
        if (line) free(line);
    }
    else printf("Can not open file\n");

    return 0;
}

getline() returns -1 when there is no more lines in file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.