Thread: setting array to 0

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    19

    setting array to 0

    Hello everyone,

    I'm learning about code used to open files.

    I got the following code from "Sam's Teach Yourself C for Linux Programming"

    I don't understand why he set filename[ ] and mode [ ] to 0.
    Code:
    /*demonstrating the fopen( )*/
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void)
    {
       FILE *fp;
       char ch, filename[40], mode[5];
    
       while (1)
    
       {
            printf("\nEnter a filename: ");
            fgets(filename, 40, stdin);
            filename[ strlen(filename) - 1] = 0;  /*sets filename[ ] to 0 ????*/
            printf("\nEnter a mode (max 3 characters): ");
            fgets(mode, 5, stdin);
            mode [ strlen(mode) - 1] = 0; /*sets mode[ ] to 0 ????*/
    
            /*then opens file with--- */
    
             if ( ( fp = fopen( filename, mode ) ) != NULL )
    
          /* etc. .....*/
    Thanks

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    mode [ strlen(mode) - 1] = 0;
    This will strip the newline off of mode. fgets() sometimes adds a newline onto the end.

    It should really be
    Code:
    if(mode[strlen(mode)-1] == '\n') mode[strlen(mode)-1] = 0;
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    19
    That has to be the fastest response I have ever had on a post.
    (less than 5 minutes)
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. setting structure char array with string
    By Tom Bombadil in forum C Programming
    Replies: 6
    Last Post: 04-03-2009, 07:10 AM
  2. Little Array Difficulty
    By G4B3 in forum C Programming
    Replies: 16
    Last Post: 03-19-2008, 12:59 AM
  3. Setting all elements of an array to zero
    By kolistivra in forum C Programming
    Replies: 9
    Last Post: 08-29-2006, 02:42 PM
  4. help setting an array please.
    By axlton in forum C++ Programming
    Replies: 4
    Last Post: 07-11-2003, 11:01 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM