Reputation: 1
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
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
Reputation: 400049
There are some fishy things:
feof()
like that, it's not what it's for and it won't work.25
characters, that's not very long (your longest word seems to be 14 characters though, so it should be fine).fscanf()
(in fact, that can be used to replace feof()
).Upvotes: 1