help with my getc

This is a discussion on help with my getc within the C Programming forums, part of the General Programming Boards category; im new to program and have written a bit of code for my class but i want it to display ...

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    9

    help with my getc

    im new to program and have written a bit of code for my class but i want it to display a error message rather than crash if the user enters a invalid file name? i think i should use a if statment but i cant get the sintax right.

    Code:
    
    #include <stdlib.h>
    #include <stdio.h>
    //a program that reads in a text file chosen by the user character by character and prints it out on the screen by Thomas collyer 01.12.10
    void main ()//defines a program called main
    {
    FILE *file_in;//defines the stream as file in
    char letter, destination[30]; //defines a string for each character and and array for the name of the text file
     
    printf("please enter the file destination you want to read in\n");//gets the user to enter a file
    scanf("%s" , destination);//reads in the destination and stores it in destination variable
    file_in=fopen(destination, "r");// opens and reads the file
    do//reads in the file and prints the file untill the end of file condition is met.
    {
    
    letter=getc(file_in);//reads each letter in one at a time to the letter variable
    printf("%c" , letter);//prints each letter out on the screen
    }
    while
    
    (letter != EOF);//checks if has reached the end of the text file
    fclose(file_in);//closes the stream
    }

  2. #2
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,652
    If the filename is invalid, then fopen will return a NULL pointer. Therefore you should check the value of file_in to see if it's NULL, and if it is, do not do anything else with that FILE * and exit the program or otherwise handle the issue.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getc Seg Fault
    By Tyris in forum C Programming
    Replies: 3
    Last Post: 05-25-2005, 01:00 PM
  2. fgets after getc
    By viaxd in forum C Programming
    Replies: 3
    Last Post: 12-03-2003, 09:24 AM
  3. fgetc() and getc()
    By The Dog in forum C Programming
    Replies: 2
    Last Post: 07-24-2002, 06:00 AM
  4. diff btn getc() & getchar()
    By Kokila in forum C Programming
    Replies: 6
    Last Post: 11-29-2001, 11:16 PM
  5. getc or not getc that is the problem
    By Juan Roberto in forum C Programming
    Replies: 3
    Last Post: 11-13-2001, 12:43 PM

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