C: Advanced I/O and Command Line

🗓 Last updated: 2026-11-30👤 Written by: Harper✓ Reviewed by: Dana🏷 Category: C Tutorial

Command-line arguments are like ordering at a restaurant — you tell the program what you want (argv), the program counts how many items you ordered (argc), and then prepares your order.

Reference entries in this section: atoi strtol sprintf

1. Command-Line Arguments

(1) argc and argv

The main function can receive two parameters:

TEXT
int main(int argc, char *argv[])
C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(int argc, char *argv[]) {
    // I/O operation
    printf("Argument count: %d\n", argc);
    // For loop
    for (int i = 0; i < argc; i++) {
        // I/O operation
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    // Return result
    return 0;
}

Run:

BASH
./program hello world 123
TEXT
Argument count: 4
argv[0] = ./program
argv[1] = hello
argv[2] = world
argv[3] = 123
💡 Tip: Command-line arguments are all strings! If you need numbers, you must convert them using atoi, atol, or strtol.

(2) Argument Parsing in Practice

In real projects, command-line arguments typically use - prefixes for options:

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

int main(int argc, char *argv[]) {
    int verbose = 0;
    int count = 1;
    const char *filename = NULL;

    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
            verbose = 1;
        } else if (strcmp(argv[i], "-n") == 0 && i + 1 < argc) {
            count = atoi(argv[++i]);
        } else if (argv[i][0] != '-') {
            filename = argv[i];
        } else {
            fprintf(stderr, "Unknown option: %s\n", argv[i]);
            return 1;
        }
    }

    if (filename == NULL) {
        fprintf(stderr, "Usage: %s [-v] [-n count] filename\n", argv[0]);
        return 1;
    }

    printf("File: %s, Count: %d, Verbose: %s\n",
           filename, count, verbose ? "on" : "off");
    return 0;
}
⚠️ Note: Manual argument parsing is error-prone. Complex projects can use the getopt function, which handles both short and long option combinations.


2. Environment Variables

(1) getenv

C
// Function definition
char *getenv(const char *name);

Returns the value of the environment variable, or NULL if it doesn't exist.

C
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>

// Function definition
int main(void) {
    const char *path = getenv("PATH");
    // Conditional check
    if (path != NULL) {
        // I/O operation
        printf("PATH = %s\n", path);
    }

    const char *home = getenv("HOME");
    // Conditional check
    if (home != NULL) {
        // I/O operation
        printf("HOME = %s\n", home);
    }
    // Return result
    return 0;
}

(2) The extern Variable environ

C defines a global variable environ that points to an array of all environment variable strings:

C
// Preprocessor directive
#include <stdio.h>

extern char **environ;

// Function definition
int main(void) {
    char **env = environ;
    // While loop
    while (*env) {
        // I/O operation
        printf("%s\n", *env);
        env++;
    }
    // Return result
    return 0;
}
💡 Tip: Environment variables are commonly used to configure program behavior, such as database connection strings and log levels. This is much more flexible than hardcoding values into source code.


3. errno Error Handling

(1) The errno Mechanism

When C standard library functions encounter errors, they typically don't crash directly. Instead, they set the global variable errno and return an error value:

C
// Preprocessor directive
#include <errno.h>

errno is not automatically cleared to zero after a successful library function call! You must only check it after a function call has failed.

(2) perror / strerror

C
// Function definition
void perror(const char *s);
// Function definition
char *strerror(int errnum);

perror outputs s: error message to stderr. strerror returns the text description corresponding to the error code.

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

int main(void) {
    FILE *fp = fopen("nonexistent_file.txt", "r");
    if (fp == NULL) {
        perror("fopen");
        printf("Error code: %d, Error message: %s\n", errno, strerror(errno));
        return 1;
    }
    fclose(fp);
    return 0;
}
TEXT
fopen: No such file or directory
Error code: 2, Error message: No such file or directory

▶ Example

Complete error handling pattern:

▶ Try it Yourself
⚠️ Note: ferror checks whether a stream has experienced a read/write error, which is different from feof (which checks for end of file).


4. Standard Streams

C automatically opens three streams when a program starts:

Stream Name Default Device File Descriptor
stdin Standard input Keyboard 0
stdout Standard output Screen 1
stderr Standard error Screen 2

The difference between stdout and stderr: stdout is buffered, stderr is unbuffered. When redirecting, they do not affect each other.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    fprintf(stdout, "This is normal output\n");
    fprintf(stderr, "This is error output\n");
    // Return result
    return 0;
}
BASH
./program > output.txt

After running this way, "normal output" goes to the file, while "error output" still appears on the screen.

(1) Redirection Principles

At the command line:

BASH
./program 2>&1 all.log

This command merges stderr into stdout and writes both to all.log.


5. Temporary Files

(1) tmpfile

C
FILE *tmpfile(void);

Creates a temporary file opened in "wb+" mode. The file is automatically deleted when closed or when the program ends.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    FILE *tmp = tmpfile();
    // Conditional check
    if (tmp == NULL) {
        perror("tmpfile");
        // Return result
        return 1;
    }

    fprintf(tmp, "Temporary data %d\n", 42);
    rewind(tmp);

    char buf[64];
    // While loop
    while (fgets(buf, sizeof(buf), tmp) != NULL) {
        // I/O operation
        printf("%s", buf);
    }

    // I/O operation
    fclose(tmp);
    // Return result
    return 0;
}
TEXT
Temporary data 42

(2) tmpnam

C
// Function definition
char *tmpnam(char *s);

Generates a temporary file name that doesn't conflict with existing files. However, there's a race condition — between generating the name and creating the file, another program could create a file with the same name.

⚠️ Note: Prefer tmpfile — it atomically creates and opens the file, making it safer. tmpnam is not safe in multi-threaded environments.

▶ Example

Using a temporary file to process intermediate data:

▶ Try it Yourself
TEXT
Before sorting:
  banana
  apple
  orange
  grape
After sorting:
  apple
  grape
  orange
  banana

6. Advanced Formatted Output

(1) snprintf

C
// Function definition
int snprintf(char *str, size_t size, const char *format, ...);

Compared to sprintf, snprintf adds a size parameter to limit the write length, preventing buffer overflow.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    char buf[10];
    // Variable declaration
    int n = snprintf(buf, sizeof(buf), "Hello, %s!", "World");
    // I/O operation
    printf("buf = \"%s\", required length = %d\n", buf, n);
    // Return result
    return 0;
}
TEXT
buf = "Hello, Wo", required length = 13
💡 Tip: The return value of snprintf is the length that the formatted output should have, not the actual number of bytes written. If the return value is greater than size-1, the output was truncated.

Reference entries in this section: atoi strtol sprintf

❓ FAQ

Q What is the order of arguments in argv?
A argv[0] is the program name itself, and argv[1] onward are the user-supplied arguments, in the same order as on the command line. argc counts them all, so argc == 1 means no user arguments were provided.
Q Why does perror output to stderr instead of stdout?
A Because error messages should not be lost when stdout is redirected to a file. stderr is independent from stdout — when you run ./program > output.txt, error messages still print to the terminal while stdout goes to the file.
Q When is errno cleared to zero?
A It is never automatically cleared. You must manually set errno = 0 before calling a function that might fail, then check errno after the function returns an error value. Some functions (like malloc) may not set errno on certain failure paths, so check the return value first.
Q Where does tmpfile create its file?
A The location is system-dependent (typically a temp directory like /tmp on Linux). You do not need to care about the path because tmpfile returns a FILE pointer, and the file is automatically deleted when it is closed or when the program ends.
Q How to generate a random int in C?
A rand() from stdlib.h returns an integer between 0 and RAND_MAX. Seed with srand((unsigned)time(NULL)) once at program start. To get [0, n), use rand() % n. To get [lo, hi], use lo + rand() % (hi - lo + 1).
Q Should I cast the result of malloc (in C)?
A No. malloc returns void *, which C automatically converts to any pointer type. Casting makes no difference to correctness in pure C.
Q What is the difference between ++i and i++?
A Both increment i by 1, but ++i (pre-increment) returns the new value while i++ (post-increment) returns the old value. In for loops the final value is thrown away anyway, so either works.
Q Is less than faster than less than or equal?
A No. On modern CPUs, < and <= compile to the same comparison instruction followed by a different branch condition. The actual comparison cost is identical.

▶ Example — argc argv and getenv

▶ Try it Yourself
TEXT
argc = 3
  argv[0] = ./myprog
  argv[1] = hello
  argv[2] = world
HOME = /root

📖 Summary

📝 Exercises

  1. Write a command-line program that accepts -c to count characters, -l to count lines, and -w to count words in a file
  2. Write a program that uses tmpfile to reverse the contents of a file (write everything to a temporary file, then read it back in reverse order)
  3. Write a program that demonstrates the difference between stdout and stderr redirection, using > and 2> to capture each type of output separately
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏