[C] Fichiers
Introduction
Le langage C permet de sauvegarder ou de lire du texte et du contenu binaire dans des fichiers.
Exemple
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to save text into a file
void saveText(const char *fileName, const char *text) {
FILE *file = fopen(fileName, "w"); // Open the file in write mode
if (file == NULL) {
fprintf(stderr, "Error opening file %s\n", fileName);
return;
}
// Write the text into the file
fprintf(file, "%s", text);
fclose(file); // Close the file
printf("Text saved to file %s\n", fileName);
}
// Function to read text from a file
void readText(const char *fileName) {
FILE *file = fopen(fileName, "r"); // Open the file in read mode
if (file == NULL) {
fprintf(stderr, "Error opening file %s\n", fileName);
return;
}
char line[100]; // Buffer to store each line read from the file
printf("Contents of file %s:\n", fileName);
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line); // Display the text line by line
}
fclose(file); // Close the file
}
int main() {
const char *fileName = "myFile.txt";
const char *text = "Hello, I am text saved into a file.\nI hope you are doing well!";
// Save text into a file
saveText(fileName, text);
// Read text from the file
readText(fileName);
return 0;
}