Thread: Opening input file

  1. #1
    Registered User
    Join Date
    May 2004

    Question Opening input file

    My program asks the user for the name of the input file.
    If the user screws up and enters nothing, or an incorrect filename, the program will crash. How can the program be directed to recognize that the specified file does not exist and instead of crashing, display an error message and exit.

    the filename is put into a variable called inname, and then variable used to open the file. like so:

    // Lets figure out what the user has called the file, and load it up
    printf( "\n\n\tName of input file: " );
    scanf( "%s", &inname );
    inp = fopen(inname, "r");

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Ontario, Canada
    If the file doesn't exist, fopen() returns NULL.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    #include <stdlib.h> /*for exit*/
         perror("Couldn't open file\n");

  4. #4
    Registered User
    Join Date
    May 2004
    i was browsing threads and found the answer like 2mins after. that'll learn me to post quickly.

    it was exactly like your suggestion. thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. fscanf in different functions for the same file
    By bchan90 in forum C Programming
    Replies: 5
    Last Post: 12-03-2008, 09:31 PM
  3. Trouble with a lab
    By michael- in forum C Programming
    Replies: 18
    Last Post: 12-06-2005, 11:28 PM
  4. File I/O with 2 input and 1 output file
    By Sandy in forum C Programming
    Replies: 1
    Last Post: 04-19-2003, 12:06 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM