Thread: Character Array: If Null

  1. #1
    Registered User
    Join Date
    Mar 2005

    Character Array: If Null


    Im having a really simple problem.
    I have an if statement to check if an input from a user is empty or not, if it is then the program needs to take one course of action. if it isnt then it uses it.

    Its a prompt for a filename to save some variables to, reading into a character array[20] called filename, I will be changing from gets to something else shortly but I want to get the if statement working first.

    printf("Enter filename");
    if(filename == NULL)
    savefile = fopen("default.dat","w");
    savefile = fopen(filename, "w");
    now before I had the option to enter a filename it automatically it would save to default.dat with that exact same line. Now it doesnt seem to register that filename is null when I dont input anything.
    Is this because its an array so I cant use a simple if == Null statement?

    or, because its picking up some random place in memory its never actually empty?

    Thanks for any pointers.

  2. #2
    Registered User
    Join Date
    Jan 2005
    looking at you code i have found some bugs
    1. shouldn't use gets to read a string read FAQ for more information for not using gets instead use fgets

    syntax for fgets
    fgets(char *, int, FILE *);
    and your actual problem, try out the follwing code

    char file[20];
    printf("Enter the file name\n?");
    fgets(file,sizeof file, stdin);
    hope this helps


  3. #3
    Registered User
    Join Date
    Mar 2005
    Thats great thanks

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    One thing you'll need to remember is that fgets keeps the newline in the buffer it fills if there is one. So you'll want to check for that and remove it. (Otherwise it will try to open a file whose name includes a newline, and probably fail on opening.)

    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. "Virtual Printer" or "Moving Printjobs"
    By extasic in forum Windows Programming
    Replies: 12
    Last Post: 06-30-2011, 08:33 AM
  2. addrinfo Structure Not Working
    By pobri19 in forum Networking/Device Communication
    Replies: 9
    Last Post: 10-22-2008, 10:07 AM
  3. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  4. Why am I getting these errors??
    By maxthecat in forum Windows Programming
    Replies: 3
    Last Post: 02-03-2006, 01:00 PM
  5. . . . . . . - . . . - -
    By The Brain in forum C++ Programming
    Replies: 17
    Last Post: 05-17-2005, 04:01 AM