ant2009
ant2009

Reputation: 22676

Displaying standard error messages

I am just testing a small program that I want to test.

I am wondering if there is a way to use the stderr to display what the actual error was.

For example, if the file doesn't exist. Is there a standard error that I can display.

I am using stderr, and I thought by using that, I could display what the actual error was.

For example. If the file doesn't exit. Does any errors get sent to stderr that can be displayed?

I hope I am clear with my question.

Many thanks for any advice.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buffer[100] = {'\0'}; /* declare and clean buffer */

    FILE *fp;
    int len_of_buff = 0;

    fp = fopen("licenseURL.txt", "r");

    if(fp == NULL)
    {
        fprintf(stderr, "There was a error opening a file ???");

        exit(1);
    }

    fgets(buffer, sizeof(buffer), fp);
    len_of_buff = strlen(buffer);
    buffer[len_of_buff + 1] = '\0'; /* null terminate */
    printf("The url is: [ %s ]\n", buffer);

    fclose(fp);
}

Upvotes: 0

Views: 759

Answers (3)

anselm
anselm

Reputation: 792

My untested version would look like this:


#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void
die(const char *errstr, ...) {
        va_list ap;

        va_start(ap, errstr);
        vfprintf(stderr, errstr, ap);
        va_end(ap);
        exit(EXIT_FAILURE);
}

int
main(int argc, char **argv) {
        static const char licenseURL[] = "licenseURL.txt";
        static char buf[100]; /* declare a clean buffer */
        FILE *fp;
        size_t len = 0;

        if(!(fp = fopen(licenseURL, "r")))
                die("couldn't %s: %s\n", licenseURL, strerror(errno));
        if(!fgets(buf, sizeof buf, fp))
                die("fgets failed: %s\n", strerror(errno));
        len = strlen(buf);
        if(len > 1 && buf[len - 1] == '\n')
                buf[len - 1] = '\0'; /* cut off trailing \n */
        printf("The url is: [ %s ]\n", buf);
        fclose(fp);

        return 0;
}

Upvotes: 1

caf
caf

Reputation: 239321

Replace your fprintf(stderr, ...) call with:

perror("file open");

(stderr is just a stream for sending error messages to, so that they don't get mixed up with the normal program output - in case you're redirecting to a file or similar).

Upvotes: 5

David Schmitt
David Schmitt

Reputation: 59375

Use the strerror() function to retrieve a string describing the error.

Upvotes: 3

Related Questions