Thread: Can someone help me??

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    1

    Can someone help me??

    I need some help with this code is is suppose to open a file "jojo" and find out how many words are in it. then out print that however i seem to be importing the file wrong can someone help me fix that?



    #include <stdio.h>

    int main(void)
    {
    FILE *fp;
    int c;
    char b[1000];
    int n=0;

    fp = fopen("jojo.txt", "r"); // error check this!

    // this while-statement assigns into c, and then checks against EOF:

    while((c = fgetc(fp)) != EOF)
    {
    if (c == ' ')
    {
    n++;
    }
    }


    fclose(fp);
    printf("This file has %d words", n);

    return 0;
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Test your file pointer after the open the file line of code, and see if it's address is NULL. If it is NULL, then print an unable to open the file error message, and return. Don't try to keep running the program like normal.

    Pretty much what your //comment has to say. Good advice!

  3. #3
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    Use code tags, please. Like Adak said, you should check if the file exists before continuing the program, and print an error message and return 1 if it doesn't.

    The program looks fine to me, but you declared an array that you didn't use.
    Quote Originally Posted by The Jargon File
    Microsoft Windows - A thirty-two bit extension and graphical shell to a sixteen-bit patch to an eight-bit operating system originally coded for a four-bit microprocessor which was written by a two-bit company that can't stand one bit of competition.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed