how can i open a data file to run this program?

Discussion in 'Mac Programming' started by manee, Sep 5, 2011.

  1. manee, Sep 5, 2011
    Last edited by a moderator: Sep 6, 2011

    manee macrumors newbie

    Joined:
    Sep 5, 2011
    #1
    Code:
    #include <stdio.h>
    
    #define EOF -1
    
    
    main()
    {
        int count,letter;
        system("pwd");
        count=0;
        letter= getchar();
        
        while(letter!= EOF)
        {
            if(letter=='e')
                ++count;
            letter=getchar();
        }
        printf("frequency %d\n",count);
    }
    this program counts the number of 'e's on a text i saved under a text file.I want to know how i can open that file. the program name is com1 and the file name is file1.

    com1<file1 doesn't work
     
  2. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #2
    Redirecting stdin works, you just need to provide the path to com1. For your current directory use ./com1 < file

    You shouldn't define EOF as it's a predefined constant, also main should return int.

    Code:
    #include <stdio.h>
    
    int main()
    {
        int count,letter;
        system("pwd");
        count=0;
        letter= getchar();
    
        while(letter != EOF)
        {
            if(letter=='e')
                ++count;
            letter=getchar();
        }
    
        printf("frequency %d\n",count);
    
        return 0;
    }
    
    You can use fopen and fread, fgetc, fgets, fscanf and so on to read from a file in the program.
     
  3. willieva macrumors 6502

    Joined:
    Mar 12, 2010
    #3
    Please post the output of your run. Except for a spurious system call and redefining EOF, everything looks fine.

    Make sue both com1 and file1 are in the current directory:
    ls com1 file1

    Perhaps '.' isn't in your path? Try running it like
    ./com1 < file1
     
  4. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #4
    Always post any error messages that appear when it doesn't work. If you got no error messages, then say that.

    Posting error messages tells us what actually happened. Otherwise we're just guessing. "It doesn't work" doesn't describe what happened.

    Here are four Rules of Thumb for posting:
    1. Be specific.
    2. Post your code.
    3. Describe what you expected to happen.
    4. Describe what actually happened.
     

Share This Page