Opening input file

This is a discussion on Opening input file within the C Programming forums, part of the General Programming Boards category; My program asks the user for the name of the input file. If the user screws up and enters nothing, ...

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    11

    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
    Location
    Ontario, Canada
    Posts
    2,718
    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
    Location
    Louisiana
    Posts
    926
    example
    Code:
    #include <stdlib.h> /*for exit*/
    ...
    if(!(fp=fopen(input,"r"))){
         perror("Couldn't open file\n");
         exit(0);
    }

  4. #4
    Registered User
    Join Date
    May 2004
    Posts
    11
    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, 08:31 PM
  3. Trouble with a lab
    By michael- in forum C Programming
    Replies: 18
    Last Post: 12-06-2005, 10: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, 01:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21