[Courses] [C] lesson 13: debugging answer

Morgon Kanter admin at surgo.net
Thu Dec 5 13:12:32 EST 2002


This one was easy to spot ;) The problem was that the inputted 
filename didn't have it's newline character trimmed off. I added a 
comment where I added the extra line to help out (and I also added 
my trim_newline function).

One other thing I changed around: I made it so it used a file descriptor 
instead. You'll see my comments. I will also post to this list a bit later 
today, about these file descriptors

/********* START *********/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
/* fcntl.h for the O_RDONLY and open() */

int trim_newline(char *string);

int main(void)
{
    int fd;           /* file descriptor */
    char  name[100];  /* name of the file to use */
    FILE  *in_file;   /* file for input */

    printf("Name? ");
    fgets(name, sizeof(name), stdin);
    /* added trim_newline here */
    trim_newline(name);
    
    /* changed this to use a file descriptor instead. 
     * Much better imo, so you can have a FILE for both 
     * reading and writing. (learned that was better in 
     * a book I am reading so if you use FILE for both 
     * read and write, it doesn't close it before everything 
     * in the buffer is written).
    */
    fd = open(name, O_RDONLY);    
    in_file = fdopen(fd, "r");
    if (in_file == NULL)
    {
        fprintf(stderr, "Could not open file\n");
        exit(8);
    }
    printf("File found\n");
    fclose(in_file);

    return 0;
}

/* Trim newline function:
 * Will trim the newline char in an inputted string. 
 * 
 * Returns 0 on success, and -1 on failure
*/
int trim_newline(char *string) {
    unsigned int i = 0;
    
    while(*(string + i) != '\0') {
    
        if(*(string + i) == '\n') {
            *(string + i) = '\0';
            return 0;
        }

        i++;
    }

    return -1;
}
/******* END *******/

output:
venthorn at surgo:~/C/lesson13$ ./debug
Name? test.file
File found
venthorn at surgo:~/C/lesson13$ ./debug
Name? blah
Could not open file



More information about the Courses mailing list