English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The fprintf() function is used to write a sequence of characters to a file. It sends formatted output to the stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
#include <stdio.h> void main() { FILE *fp; fp = fopen("file.txt", "w");//Open file fprintf(fp, "I am the data written by fprintf...\n");//Write data to file fclose(fp);//Close file }
The fscanf() function is used to read a sequence of characters from a file. It reads a word from the file and returns EOF at the end of the file.
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); }
Salida:
I am the data written by fprintf...
Let's see 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+");/* Open file in write mode */ if (fptr == NULL) { printf("File does not exist\n"); return; } printf("Input id\n"); scanf("%d", &id); fprintf(fptr, "Id= %d\n", id); printf("Input name\n"); scanf("%s", name); fprintf(fptr, "Name= %s\n", name); printf("Input salary\n"); scanf("%f", &salary); fprintf(fptr, "Salary= %.",2f\n", salary); fclose(fptr); }
Salida:
Ingrese el id 1 Ingrese el nombre sonoo Ingrese el salario 120000
Ahora abra el archivo desde el directorio actual. Para el sistema operativo Windows, vaya al directorio de archivos, donde verá el archivo emp.txt. Tendrá la siguiente información.
emp.txt
Id= 1 Nombre= sonoo Salario= 120000