Thread: file doesn't open

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    14

    file doesn't open

    when i try to open a file for example c:\file.txt it will not open. here is my code.

    Code:
    int main ()
    {
            char c; /* User defined character */
            char filename[50];
            int num = 0; /* Number of times character was found */
            FILE *inp; /* pointer to input file */
    
            printf("Enter the name of the file you wish to open: ");
            scanf ("%s", &filename);
            inp = fopen("c:%s", "r");
    
            if (inp != NULL){
               printf("OPEN");
            }else{
               printf("NOT OPEN");
            }
            
            getch();
            return 0;
    }
    it always comes back "NOT OPEN". why is this?

  2. #2
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    That's because you're literally tying to open the file "c:%s".

    You need to put the path of the file you're actually trying to open there - a format specifier won't work.

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    14
    well how would i be able to put a user specified file in there? would it be c:filename?

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    change

    inp = fopen("c:%s", "r");

    into

    inp = fopen(filename, "r");
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  5. #5
    Registered User
    Join Date
    Feb 2003
    Posts
    14
    thanks

  6. #6
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    I may be wrong, but shouldn't

    scanf ("%s", &filename);

    be

    scanf ("%s", filename);

    since filename already is a pointer (an array, but they're practically the same thing).
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  7. #7
    Registered User
    Join Date
    Feb 2003
    Posts
    14
    yeah i guess it works either way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM