English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico de Linguagem C

C Language Flow Control

Funções C

Matrizes C

Ponteiro C

String C

C Language Structures

C Language Files

C Others

C Language Reference Manual

fprintf() e fscanf() de Arquivo C

Write to file: fprintf() function

The fprintf() function is used to write character sets 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
}

Read file: fscanf() function

The fscanf() function is used to read character sets 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);
}

Saída:

I am the data written by fprintf...

C File Example: Store employee information

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("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);
}

Saída:

Insira o id 
1
Insira o nome 
sonoo
Insira o salário
120000

Agora abra o arquivo atualmente no diretório. Para o sistema operacional Windows, vá para o diretório do arquivo, onde você verá o arquivo emp.txt. Ele terá as seguintes informações.

emp.txt

Id= 1
Nome= sonoo
Salário= 120000