⬅ Previous Next ➡

Command-line & Error Handling

Command-line & Error Handling in C
  • Command-line arguments allow you to pass values to a C program while running it from terminal/command prompt.
  • Error handling in C is commonly done using errno (error code) and functions like perror() and strerror().
  • Header files used: <stdio.h>, <stdlib.h>, <string.h>, <errno.h>.

1) Command-line Arguments (argc, argv)

  • int main(int argc, char *argv[])
  • argc = number of arguments (including program name).
  • argv = array of strings (arguments).
  • argv[0] = program name, argv[1] = first argument, etc.
#include <stdio.h>

int main(int argc, char *argv[]) {

    printf("Total arguments (argc) = %d\n", argc);

    for (int i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }

    return 0;
}
// Run example:
// gcc args.c -o args
// ./args 10 20 hello

2) Converting Command-line Strings to Numbers

  • Use atoi(), atof() (simple) or strtol() (recommended).
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    if (argc < 3) {
        printf("Usage: %s num1 num2\n", argv[0]);
        return 0;
    }

    int a = atoi(argv[1]);
    int b = atoi(argv[2]);

    printf("Sum = %d\n", a + b);
    return 0;
}

3) Error Handling using errno

  • errno is a global integer set by system/library calls when an error occurs.
  • Include <errno.h>.
  • Set errno to 0 before a risky operation for correct checking.

4) perror() Function

  • perror("message") prints your message + the system error description based on errno.
  • Very useful for file-related errors.
#include <stdio.h>
#include <errno.h>

int main() {
    FILE *fp = fopen("not_found.txt", "r");

    if (fp == NULL) {
        perror("File open error");
        return 0;
    }

    fclose(fp);
    return 0;
}

5) strerror() with errno (Manual Error Message)

  • strerror(errno) returns the error message string.
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    FILE *fp = fopen("missing.txt", "r");

    if (fp == NULL) {
        printf("Error code: %d\n", errno);
        printf("Error message: %s\n", strerror(errno));
        return 0;
    }

    fclose(fp);
    return 0;
}

6) Quick Notes

  • Command-line args are always strings; convert when needed.
  • perror() is simplest for printing system errors.
  • errno helps identify why system calls failed.
  • Always validate argc before using argv indexes.
⬅ Previous Next ➡