Maison > Article > développement back-end > Bases du traitement des fichiers C
Ici, nous verrons quelques opérations de traitement de fichiers de base en langage C. Voici une liste de ces opérations :
Veuillez vous référer au code suivant pour comprendre comment écrire dans un fichier
#include <stdio.h> int main() { FILE *fp; char *filename = "sample.txt"; char *content = "Hey there! You've successfully created a file with content in c programming language."; /* open for writing */ fp = fopen(filename, "w"); if( fp == NULL ) { printf("%s: failed to open. </p><p>", filename); return -1; } else { printf("%s: opened in write mode.</p><p>", filename); } /* Write content to file */ fprintf(fp, "%s</p><p>", content); if( !fclose(fp) ) printf("%s: closed successfully.</p><p>", filename); return 0; }
sample.txt: opened in write mode. sample.txt: closed successfully.
Voir le code pour comprendre comment nous lisons à partir d'un fichier Créer un fichier (file_read.txt) :
Vous ouvrez un fichier en mode lecture seule en utilisant le langage de programmation C.
#include <stdio.h> int main() { FILE *fp; char *filename = "file_read.txt"; char ch; /* open for writing */ fp = fopen(filename, "r"); if (fp == NULL) { printf("%s does not exists </p><p>", filename); return; } else { printf("%s: opened in read mode.</p><p></p><p>", filename); } while ((ch = fgetc(fp) )!= EOF) { printf ("%c", ch); } if (!fclose(fp)) printf("</p><p>%s: closed.</p><p>", filename); return 0; }
file_read.txt: opened in read mode. You have opened a file using C programming language, in read-only mode. file_read.txt: closed.
Affichez le code pour voir comment ajouter des lignes à un fichier.
This text was already there in the file.
#include <stdio.h> int main() { FILE *fp; char ch; char *filename = "file_append.txt"; char *content = "This text is appeneded later to the file, using C programming."; /* open for writing */ fp = fopen(filename, "r"); printf("</p><p>Contents of %s -</p><p></p><p>", filename); while ((ch = fgetc(fp) )!= EOF) { printf ("%c", ch); } fclose(fp); fp = fopen(filename, "a"); /* Write content to file */ fprintf(fp, "%s</p><p>", content); fclose(fp); fp = fopen(filename, "r"); printf("</p><p>Contents of %s -</p><p>", filename); while ((ch = fgetc(fp) )!= EOF) { printf ("%c", ch); } fclose(fp); return 0; }
Contents of file_append.txt - This text was already there in the file. Appending content to file_append.txt... Content of file_append.txt after 'append' operation is - This text was already there in the file. This text is appeneded later to the file, using C programming.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!