john alanson
john alanson

Reputation: 1

File Read Error in C

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;

}

Upvotes: 0

Views: 3141

Answers (2)

Sandro Kalatozishvili
Sandro Kalatozishvili

Reputation: 602

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

Upvotes: 0

unwind
unwind

Reputation: 400049

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()).

Upvotes: 1

Related Questions