ouverture du fichier c
#include <stdio.h>
int main() {
FILE *filePointer;
char data[50];
filePointer = fopen("file.txt", "r");
if (filePointer == NULL) {
printf("File cannot be opened.\n");
return 1;
}
fscanf(filePointer, "%s", data);
printf("Data from the file: %s\n", data);
fclose(filePointer);
return 0;
}
Explanation:
#include <stdio.h>
: Includes the standard input-output header file for handling input and output operations.int main() { ... }
: Entry point of the program.FILE *filePointer;
: Declares a pointer to a FILE type, used for file operations.char data[50];
: Declares an arraydata
capable of holding 50 characters.filePointer = fopen("file.txt", "r");
: Opens a file named "file.txt" in read mode.fopen
returns a pointer to the file.if (filePointer == NULL) { ... }
: Checks if the file opening was unsuccessful. IffilePointer
isNULL
, it means the file couldn't be opened.printf("File cannot be opened.\n");
: Displays an error message if the file opening fails.fscanf(filePointer, "%s", data);
: Reads a string from the file pointed to byfilePointer
and stores it in thedata
variable.printf("Data from the file: %s\n", data);
: Prints the data read from the file.fclose(filePointer);
: Closes the file associated withfilePointer
to release resources.return 0;
: Indicates successful execution of the program.