1

I'm reading data from a file word by word and trying to store in same buffer with space between every word. But words are coming out without space. Please tell me what is wrong? output coming aniljaiswalvikaskumarnikhilkumarindia but i want space between each word.

int main()
{
    char buff[200];
    int l=0;
    FILE *fp;
    fd = NULL;``
    fp = fopen("header.c","r");
    memset(buff,0,200);
    while(1)
    {
        fscanf(fp,"%s",buff+l);
        l=strlen(buff);
        printf("Word of string = %s\n",buff);
        printf("Length of string = %d\n",l);
        if(feof(fp))
        {
            break;
        }
    }
    fclose(fp);
    return 0;
}
4
  • 2
    add space character explicitly to your buff after each scanf Commented Nov 1, 2012 at 18:13
  • 1
    Well, you never add any spaces. Where did you expect them to come from? Commented Nov 1, 2012 at 18:14
  • i think use fetc and put each character to buff ... there will not be problem with that Commented Nov 1, 2012 at 18:15
  • this output is coming i want space between them.. Commented Nov 1, 2012 at 18:40

2 Answers 2

1

Ignoring the fact that you are exposed to buffer overflow, you can simply add the space:

fscanf(fp,"%s",buff+l);
l=strlen(buff);
buff[l] = ' ';
l++;
Sign up to request clarification or add additional context in comments.

Comments

0

The full working code :

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

     int main()
        {
            char buff[200];
            FILE *fp;
            char c;
            int len=0;
            int i=0;
            fp = fopen("header.c","r");
            memset(buff,0,200);
            while((c=fgetc(fp))!=EOF)
            {
                len++;
                buff[i++]=c;
                if(c==' ' || c=='\n')
                {
                printf("Word of string = %s\n",buff);
                printf("Length of string = %d\n",len);
                }
            }

            fclose(fp);
            return 0;
        }

2 Comments

no problem..... but sometimes scanf creates problem so it's the safest way to read a file
Already ... answered.. check the 2nd answer given by Binyamin

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.