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


       int main()
   {
    FILE *file;
    char ch, str[500], a=0;
    char name[20], word[50], temp[50];
    int i,lenght=0,  b=0;
    if((file=fopen("sample.txt" , "r"))==NULL)
    {
         printf("Error while opening file\n");
         system("pause");
         exit(1);
    }    
    while (!feof(file))
     {
      fgets(str, 499, file);
      printf("%s\n",str);


       ch=fgetc(file);
       if(ch!=' ')
       {
       a++;
       word[b]=ch;
       if(a > lenght)
       lenght=a;f
       for (i=1; i<=lenght; i++)
       temp[i]= word[i];
       }
    } 
    printf("Longest word: ");
    for (i=1; i<=lenght; i++)
    {
   printf("%c", temp[i]);
        }
        printf("\n"); 
        fclose(file);
    system("pause");
    return 0;
}

Please someone help me with this,i need a C program which reads data from txt file and searchest the longest word in it,i have no more ideas on this,program seems to be working but have no output.

If you just want the longest word then read the file one word at a time, not the entire line. Do that with fscanf(). After a word is read all you have to do is call strlen() to get the word's length and compare it with the length of the most recent longest word that was read in the past.

mhm,thanks,but i didn't get the result i need,anyway,my task is to make a program wich reads data from txt file,also it must search longest word which begins with letter A.Really i tued out everythink,so i will ask you help to realise all this.Thank you.

As AD suggested, fscanf is right thing to do. update your code

I have no idea how to update it with fscanf() ,i'm beginner and i'm tying everything ,could yuo explain me more?

if you could explain me ,mby i would understand.

You first read a line from the file -- and do nothing with it.
Then you read the first character of the next line and do worthless stuff with it if it's not SPACE.
Then you go back and read the rest of that line with fgets() and do nothing with it.
Then you read the first character of the next line and do worthless stuff with it if it's not SPACE.
Then you go back and read the rest of that line...

You need to learn how to desk check your program. Sit at your desk with pen and paper and go through the program line by line filling in variable values as you go. Check to see if what you wrote makes sense.

Below is how to use fscanf() in a loop to read all the words in the text file. Notice that I did NOT have to call feof() because fscanf() will return an integer less than or equal to 0 when eof is reached. This is a more efficient way to check eof than using feof().

while( fscanf(file,word, sizeof(word)) > 0)
{
   // got one word, now check if it is the longest word
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.