0Pricing
Zig Academy · Aula

Lendo argumentos da linha de comando

Analise argv com um alocador.

Lendo argumentos da linha de comando é uma aula grátis de Zig Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Zig Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Zig Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Why Arguments Matter

A real CLI tool reacts to what the user types after its name. Those words are the command-line arguments, and reading them is step one. 🛠️

Zig Hands You Nothing Hidden

Other languages give you a magic argv variable. Zig stays explicit: you ask the std.process namespace for the arguments yourself.

const std = @import("std");

Arguments Need an Allocator

Decoding arguments may allocate memory, so Zig asks you for an allocator up front. No allocation happens behind your back.

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const a = gpa.allocator();

argsAlloc Gives a Slice

Call std.process.argsAlloc with your allocator. It returns a slice of strings, one per argument, that you fully own.

const args = try std.process.argsAlloc(a);

Free What You Allocated

Because you own that slice, you must release it with argsFree. A defer right after the call keeps cleanup automatic.

defer std.process.argsFree(a, args);

The First Argument Is the Program

By convention args[0] is the path to your own program, not user input. The real values you care about start at index 1.

const program = args[0];

Count How Many You Got

The slice carries its own length, so args.len tells you how many arguments arrived. You check it before reaching for any index.

if (args.len < 2) return error.MissingArgument;

Loop Over the Inputs

Iterate the user values by slicing past the program name. A for loop over args[1..] visits each argument in order.

for (args[1..]) |arg| {
    std.debug.print("{s}\n", .{arg});
}

Each Argument Is Bytes

Every argument is a []const u8, a slice of bytes. Comparing or parsing one is just normal Zig string work from here.

if (std.mem.eql(u8, arg, "--help")) {}

Turn Text into Numbers

Arguments arrive as text. To get a number, parse it with std.fmt.parseInt, which fails clearly if the text is not a valid integer.

const n = try std.fmt.parseInt(i32, args[1], 10);

An Iterator Alternative

Prefer streaming? std.process.argsWithAllocator gives an iterator you advance with next(), handy when you process arguments one at a time.

var it = try std.process.argsWithAllocator(a);
defer it.deinit();

Quick Check

Think about what sits at the front of the arguments slice.

Recap

You read arguments with argsAlloc, freed them with argsFree, skipped args[0], and parsed text into values. Your CLI now hears its user. 🎯

Perguntas Frequentes

A aula “Lendo argumentos da linha de comando” é grátis?

Sim — o texto completo de “Lendo argumentos da linha de comando” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Zig Academy, atualize para CoddyKit PRO. O curso de Zig Academy inclui 4 aulas no total.

O que vou aprender em “Lendo argumentos da linha de comando”?

Analise argv com um alocador. Você pratica Zig Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Zig Academy?

Nenhuma experiência prévia é necessária. Zig Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Lendo argumentos da linha de comando”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Zig Academy?

Sim. Cada aula de Zig Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Lendo argumentos da linha de comando
  2. Lendo arquivos e stdin
  3. Escrevendo a saída e códigos de saída
  4. Empacotando e lançando o binário
← Voltar para Zig Academy