Aller au contenu

Exemples sur les fichiers et les répertoires

Cette section contient des exemples liés aux opérations sur les fichiers en C. Voici la liste des fichiers sources avec leur description et des liens vers leur contenu.

Fichier Description Lien
file_copy.c Copie le texte saisi au clavier dans le fichier file.out avec read()/write() (Ctrl-D pour terminer) Voir
file_create.c Montre l'utilisation de open() pour créer un nouveau fichier Voir
file_createhuge.c Utilise lseek() pour créer un fichier énorme Voir
file_hexdump.c Utilise read() pour afficher le dump hexadécimal d'un fichier, 20 octets par ligne avec leurs caractères ASCII Voir
fs_block.c Utilise statvfs() pour extraire les informations sur la taille des blocs Voir
dup_01.c Montre dup() : crée un descripteur de fichier dupliqué (plus petit numéro disponible) qui partage la même description de fichier ouvert Voir
dup_02.c Montre dup2() : redirige stdout vers le fichier sortie.txt (comme sur la diapositive), en reproduisant l'opérateur shell > file Voir
dup_03.c Montre pipe() + dup2() : reproduit l'opérateur de tube du shell \| en connectant le stdout de l'enfant au tube lu par le parent jusqu'à EOF Voir
fork_shared_offset.c Après fork(), le parent et l'enfant partagent la position (offset) dans le fichier : l'enfant lit abc, puis le parent lit def (cours, chapitre "Fichiers et descripteurs", exercice 1) Voir

Code source

src/dup_01.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L /* dprintf() */
#include <unistd.h>    /* dup(), close(), STDOUT_FILENO */
#include <stdio.h>     /* printf(), dprintf() */
#include <stdlib.h>    /* exit() */

/**
 * @file dup_01.c
 * @brief Demonstrates dup(): duplicating a file descriptor.
 *
 * dup() creates a new file descriptor pointing to the same open file
 * description as the given one. The new descriptor is always the lowest
 * available number. Both descriptors share the same file offset and flags.
 *
 * \code{.bash}
 *   $ ./dup_01
 *   Original stdout fd : 1
 *   Duplicate fd       : 3
 *   Written via fd 1: hello from stdout
 *   Written via fd 3: hello from dup
 * \endcode
 */

/**
 * @brief Handles a fatal error and exits.
 * @param msg Error message displayed before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void) {
    int dup_fd;

    printf("Original stdout fd : %d\n", STDOUT_FILENO);

    dup_fd = dup(STDOUT_FILENO);
    if (dup_fd == -1) {
        handle_fatal_error_and_exit("dup");
    }

    printf("Duplicate fd       : %d\n", dup_fd);
    fflush(stdout); /* empty the stdio buffer before writing directly to the descriptors */

    /* Both point to the same open file description: both write to the terminal */
    dprintf(STDOUT_FILENO, "Written via fd %d: hello from stdout\n", STDOUT_FILENO);
    dprintf(dup_fd,        "Written via fd %d: hello from dup\n",    dup_fd);

    close(dup_fd);
    return EXIT_SUCCESS;
}
src/dup_02.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <unistd.h>    /* dup2(), close(), STDOUT_FILENO */
#include <fcntl.h>     /* open() */
#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */

/**
 * @file dup_02.c
 * @brief Demonstrates dup2(): redirecting stdout to a file.
 *
 * dup2(oldfd, newfd) atomically closes newfd (if open) and makes it refer
 * to the same file as oldfd. This is the mechanism shells use to implement
 * output redirection: "cmd > file.txt".
 *
 * After the dup2() call, every printf() writes to sortie.txt instead of
 * the terminal.
 *
 * \code{.bash}
 *   $ ./dup_02
 *   $ cat sortie.txt
 *   This line goes to the file, not the terminal.
 * \endcode
 */

/**
 * @brief Handles a fatal error and exits.
 * @param msg Error message displayed before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void) {
    int file_fd;

    file_fd = open("sortie.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (file_fd == -1) {
        handle_fatal_error_and_exit("open");
    }

    /* Redirect stdout (fd 1) to sortie.txt */
    if (dup2(file_fd, STDOUT_FILENO) == -1) {
        handle_fatal_error_and_exit("dup2");
    }
    close(file_fd); /* No longer needed directly */

    /* printf now writes into sortie.txt */
    printf("This line goes to the file, not the terminal.\n");

    return EXIT_SUCCESS;
}
src/dup_03.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <unistd.h>    /* pipe(), dup2(), fork(), close(), read() */
#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <sys/wait.h>  /* wait() */

/**
 * @file dup_03.c
 * @brief Demonstrates pipe() + dup2(): replicating the shell pipe operator.
 *
 * This is exactly how a shell implements "cmd1 | cmd2":
 *   1. Create a pipe.
 *   2. Child  (cmd1): dup2 the write-end over stdout, then write.
 *   3. Parent (cmd2): read from the read-end (a shell would also dup2 it
 *      over stdin before exec-ing cmd2).
 *
 * Closing the unused pipe ends is essential: the reader only gets EOF once
 * every write-end is closed.
 *
 * \code{.bash}
 *   $ ./dup_03
 *   Parent received: Hello from the child via a pipe!
 * \endcode
 */

#define BUFFER_SIZE 128

/**
 * @brief Handles a fatal error and exits.
 * @param msg Error message displayed before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the child process.
 *
 * Redirects stdout to the pipe write-end, then writes a message.
 * @param pipefd The pipe file descriptors.
 */
void manage_child(int pipefd[2]) {
    close(pipefd[0]); /* Child does not read from the pipe */

    if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
        handle_fatal_error_and_exit("dup2");
    }
    close(pipefd[1]);

    /* stdout now points to the pipe write-end */
    printf("Hello from the child via a pipe!\n");
    exit(EXIT_SUCCESS);
}

/**
 * @brief Manages the parent process.
 *
 * Reads the child's message from the pipe read-end and prints it.
 * @param pipefd The pipe file descriptors.
 */
void manage_parent(int pipefd[2]) {
    char buffer[BUFFER_SIZE];
    size_t total = 0;
    ssize_t n = 0;

    close(pipefd[1]); /* Parent does not write to the pipe */

    /* Read until EOF (read() returns 0): the message may come in pieces */
    while (total < sizeof(buffer) - 1
           && (n = read(pipefd[0], buffer + total, sizeof(buffer) - 1 - total)) > 0) {
        total += (size_t) n;
    }
    if (n == -1) {
        handle_fatal_error_and_exit("read");
    }
    buffer[total] = '\0';
    close(pipefd[0]);

    printf("Parent received: %s", buffer);
    if (wait(NULL) == -1) {
        perror("wait");
    }
}

int main(void) {
    int pipefd[2];
    pid_t pid;

    if (pipe(pipefd) == -1) {
        handle_fatal_error_and_exit("pipe");
    }

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }

    if (pid == 0) {
        manage_child(pipefd);
    } else {
        manage_parent(pipefd);
    }

    return EXIT_SUCCESS;
}
src/file_copy.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>  /* write and read */
#include <stdio.h>   /* perror() */
#include <fcntl.h>   /* open, O_CREAT, O_WRONLY */
#include <stdlib.h>  /* exit */

/**
 * @file file_copy.c
 *
 * Copies the text typed on the keyboard to a file named file.out. It reads input 
 * from the keyboard and writes it to the file until there is no more input.
 */

#define SIZE            80

int main(void) {
    int fd;
    ssize_t nbcar;
    char buffer[SIZE] = {0};

    fd = open("file.out", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (fd == -1) {
        perror("Error opening file.out");
        exit(EXIT_FAILURE);
    }

    const char prompt[] = "Type your input (Ctrl+D to end):\n";
    write(STDOUT_FILENO, prompt, sizeof(prompt) - 1); /* without the final '\0' */

    while ((nbcar = read(STDIN_FILENO, buffer, SIZE)) > 0) {
        if (write(fd, buffer, (size_t) nbcar) == -1) {
            perror("Error writing file.out");
            close(fd);
            exit(EXIT_FAILURE);
        }
    }
    if (nbcar == -1) {
        perror("Error reading standard input");
        close(fd);
        exit(EXIT_FAILURE);
    }

    if (close(fd) == -1) {
        perror("Error closing file");
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
src/file_create.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <fcntl.h>     /* open() opening flags and file modes */
#include <unistd.h>    /* close() */
#include <sys/stat.h>
#include <sys/types.h>

/**
 * @file file_create.c
 *
 * Demonstrates the use of the open() system call to safely create a new file
 * with specified permissions.
 */

/**
 * @brief Handles a fatal error and exits the program. 
 * Displays the provided error message using perror and exits with failure.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    int fd;         /* File descriptor */
    char *filename; /* Path at which to create the new file.  */
    mode_t mode;    /* Permissions for the new file.  */

    /* argc should be 2 */
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    filename = argv[1];
    mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH; /* User and group read/write, others read */

    /* Create the file */
    fd = open(filename, O_WRONLY | O_EXCL | O_CREAT, mode);
    if (fd == -1) {
        handle_fatal_error_and_exit("Error [open()]");
    }

    if (close(fd) == -1) {
        perror("Error closing file");
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
src/file_createhuge.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>      /* printf() */
#include <stdlib.h>     /* exit() */
#include <fcntl.h>      /* open() opening flags and file modes */
#include <unistd.h>     /* close() */
#include <sys/stat.h>
#include <sys/types.h>

#define GIGABYTE (1024LL * 1024 * 1024)

/**
 * @file file_createhuge.c
 *
 * A simple example that uses the lseek() primitive to create a huge file.
 */

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    int fd;
    char zero;
    char *filename;
    off_t length;

    /* argc should be 3 */
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <filename> <number of gigabytes>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    zero = 0;
    filename = argv[1];
    int gigabytes = atoi(argv[2]);
    if (gigabytes <= 0) {
        fprintf(stderr, "Number of gigabytes must be positive.\n");
        exit(EXIT_FAILURE);
    }

    length = (off_t)gigabytes * GIGABYTE;

    /* Open a new file. */
    fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if (fd == -1) {
        handle_fatal_error_and_exit("Error [open()]");
    }

    /* Jump to where we want the file to end. */
    if (lseek(fd, length - 1, SEEK_SET) == -1) {
        handle_fatal_error_and_exit("Error [lseek()]");
    }

    /* Write a single 0 byte. */
    if (write(fd, &zero, 1) != 1) {
        handle_fatal_error_and_exit("Error [write()]");
    }

    if (close(fd) == -1) {
        perror("Error closing file");
        exit(EXIT_FAILURE);
    }

    printf("Successfully created a %d gigabyte file '%s'.\n", gigabytes, filename);

    return EXIT_SUCCESS;
}
src/file_hexdump.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <fcntl.h>     /* open() opening flags and file modes */
#include <unistd.h>    /* read() and close() */
#include <sys/stat.h>
#include <sys/types.h>

#define BUFFER_SIZE 20

/**
 * @file file_hexdump.c
 *
 * An example of using \c the read primitive to display the hexadecimal dump of
 * a file.
 */

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    int fd;
    unsigned char buffer[BUFFER_SIZE];
    ssize_t bytes_read;
    size_t offset = 0;
    int i;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename> - Display the hexadecimal dump of a file\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    fd = open(argv[1], O_RDONLY);
    if (fd == -1) {
        handle_fatal_error_and_exit("Error opening file");
    }

    while ((bytes_read = read(fd, buffer, BUFFER_SIZE)) > 0) {
        printf("0x%06zx : ", offset);
        for (i = 0; i < bytes_read; ++i) {
            printf("%02x ", buffer[i]);
        }
        for (i = bytes_read; i < BUFFER_SIZE; ++i) {
            printf("   "); /* last line: keep the ASCII column aligned */
        }
        printf(" | ");
        for (i = 0; i < bytes_read; ++i) {
            printf("%c", (buffer[i] >= 32 && buffer[i] <= 126) ? buffer[i] : '.');
        }
        printf("\n");
        offset += bytes_read;
    }

    if (bytes_read == -1) {
        handle_fatal_error_and_exit("Error reading file"); /* before close(): errno */
    }

    if (close(fd) == -1) {
        perror("Error closing file");
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
src/fork_shared_offset.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <fcntl.h>     /* open() */
#include <unistd.h>    /* fork(), read(), write(), close() */
#include <stdio.h>     /* printf(), perror() */
#include <stdlib.h>    /* exit() */
#include <string.h>    /* strlen() */
#include <sys/wait.h>  /* wait() */

/**
 * @file fork_shared_offset.c
 * @brief After fork(), parent and child share the file offset.
 *
 * Course "Operating Systems", chapter "Fichiers et descripteurs",
 * exercise 1 ("position partagée").
 *
 * fork() copies the file descriptor table, not the open file description:
 * both processes therefore share the same current position. The child
 * reads "abc", so the parent then reads from offset 3 and prints "def".
 *
 * \code{.bash}
 *   $ ./fork_shared_offset
 *   def
 * \endcode
 */

#define FILENAME "f.txt"

/**
 * @brief Handles a fatal error and exits.
 * @param msg Error message displayed before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Creates the file used by the exercise, containing "abcdef".
 */
void create_test_file(void) {
    const char *content = "abcdef";
    int fd = open(FILENAME, O_WRONLY | O_CREAT | O_TRUNC, 0644);

    if (fd == -1) {
        handle_fatal_error_and_exit("open (creation)");
    }
    if (write(fd, content, strlen(content)) == -1) {
        handle_fatal_error_and_exit("write");
    }
    close(fd);
}

int main(void) {
    pid_t pid;

    create_test_file();

    /* Code of the exercise */
    int fd = open(FILENAME, O_RDONLY);
    char buf[4] = "";

    if (fd == -1) {
        handle_fatal_error_and_exit("open");
    }

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {             /* child */
        if (read(fd, buf, 3) == -1) {
            perror("read (child)");
        }
        exit(EXIT_SUCCESS);
    }
    if (wait(NULL) == -1) {     /* parent */
        handle_fatal_error_and_exit("wait");
    }
    if (read(fd, buf, 3) == -1) {
        handle_fatal_error_and_exit("read (parent)");
    }
    printf("%s\n", buf);

    close(fd);
    return EXIT_SUCCESS;
}
src/fs_block.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/statvfs.h> /* statvfs() */

/**
 * @file fs_block.c
 *
 * Demonstrates how to use statvfs() to extract the block size of a 
 * filesystem. The block size is a key metric for understanding filesystem
 * allocation and performance.
 */

int main(int argc, char *argv[]) {
    struct statvfs fs_stats;
    int result;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <path to any directory or file on the target filesystem>\n", argv[0]);
        printf("This program returns the block size of the filesystem containing the given path.\n");
        exit(EXIT_FAILURE);
    }

    result = statvfs(argv[1], &fs_stats);
    if (result == -1) {
        perror("Error retrieving filesystem statistics");
        exit(EXIT_FAILURE);
    }

    printf("Filesystem block size: %lu bytes\n", fs_stats.f_bsize);
    /* The block counts below are expressed in f_frsize units, not f_bsize */
    printf("Fragment size (unit of the counts below): %lu bytes\n", fs_stats.f_frsize);
    printf("Total blocks: %llu\n", (unsigned long long) fs_stats.f_blocks);
    printf("Free blocks: %llu\n", (unsigned long long) fs_stats.f_bfree);
    printf("Available blocks (non-superuser): %llu\n", (unsigned long long) fs_stats.f_bavail);

    return EXIT_SUCCESS;
}