English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La funzione fprintf() viene utilizzata per scrivere un set di caratteri in un file. Invia l'output formattato al flusso.
Syntax:
int fprintf(FILE *stream, const char *format[, argument, ...])
#include <stdio.h> void main(){ FILE *fp; fp = fopen("file.txt", "w"); // Open the file fprintf(fp, "I am the data written by fprintf...\n"); // Write data to the file fclose(fp); // Close the file }
The fscanf() function is used to read character sets from a file. It reads a word from the file and returns EOF when the end of the file is reached.
Syntax:
int fscanf(FILE *stream, const char *format[, argument, ...])
#include <stdio.h> void main(){ FILE *fp; char buff[255];// Create a char array to store file data fp = fopen("file.txt", "r"); while(fscanf(fp, "%s", buff) != EOF){ printf("%s ", buff); } fclose(fp); }
Output:
I am the data written by fprintf...
Let's look at a file processing example that stores employee information entered by the user from the specified console. We will store the employee's ID, name, and salary.
#include <stdio.h> void main(){ FILE *fptr; int id; char name[30]; float salary; fptr = fopen("emp.txt", "w+");/* Apri il file in scrittura */ if (fptr == NULL) { printf("File does not exist\n"); return; } printf("Enter id\n"); scanf("%d", &id); fprintf(fptr, "Id= %d\n", id); printf("Enter name\n"); scanf("%s", name); fprintf(fptr, "Name= %s\n", name); printf("Enter salary\n"); scanf("%f", &salary); fprintf(fptr, "Salary= %.2f\n", salary); fclose(fptr); }
Output:
Inserisci l'id 1 Inserisci il nome sonoo Inserisci lo stipendio 120000
Ora apri il file dalla directory corrente. Per il sistema operativo Windows, vai alla directory dei file, dove vedrai il file emp.txt. Avrà le seguenti informazioni.
emp.txt
Id= 1 Nome= sonoo Stipendio= 120000