E / S de arquivos C: Abrindo, lendo, gravando e fechando um arquivo

Neste tutorial, você aprenderá sobre manipulação de arquivos em C. Você aprenderá a lidar com I / O padrão em C usando fprintf (), fscanf (), fread (), fwrite (), fseek () etc. com a ajuda de exemplos.

Um arquivo é um contêiner em dispositivos de armazenamento de computador usados ​​para armazenar dados.

Por que os arquivos são necessários?

  • Quando um programa é encerrado, todos os dados são perdidos. Armazenar em um arquivo preservará seus dados, mesmo que o programa seja encerrado.
  • Se você precisar inserir um grande número de dados, levará muito tempo para inserir todos eles.
    No entanto, se você tiver um arquivo contendo todos os dados, poderá acessar facilmente o conteúdo do arquivo usando alguns comandos em C.
  • Você pode mover facilmente seus dados de um computador para outro sem qualquer alteração.

Tipos de arquivos

Ao lidar com arquivos, existem dois tipos de arquivos que você deve conhecer:

  1. Arquivos de texto
  2. Arquivos binários

1. Arquivos de texto

Os arquivos de texto são os arquivos .txt normais . Você pode criar arquivos de texto facilmente usando qualquer editor de texto simples, como o Bloco de notas.

Ao abrir esses arquivos, você verá todo o conteúdo do arquivo como texto simples. Você pode editar ou excluir facilmente o conteúdo.

Eles exigem o mínimo de esforço para manter, são facilmente legíveis e fornecem o mínimo de segurança e ocupam maior espaço de armazenamento.

2. Arquivos binários

Os arquivos binários são principalmente os arquivos .bin no seu computador.

Em vez de armazenar dados em texto simples, eles os armazenam na forma binária (0's e 1's).

Eles podem conter uma quantidade maior de dados, não são legíveis facilmente e oferecem melhor segurança do que arquivos de texto.

Operações de arquivo

Em C, você pode realizar quatro operações principais em arquivos, sejam de texto ou binários:

  1. Criação de um novo arquivo
  2. Abrindo um arquivo existente
  3. Fechando um arquivo
  4. Ler e gravar informações em um arquivo

Trabalhando com arquivos

Ao trabalhar com arquivos, você precisa declarar um ponteiro do tipo arquivo. Esta declaração é necessária para a comunicação entre o arquivo e o programa.

 FILE *fptr;

Abrindo um arquivo - para criação e edição

A abertura de um arquivo é realizada usando a fopen()função definida no stdio.harquivo de cabeçalho.

A sintaxe para abrir um arquivo no I / O padrão é:

 ptr = fopen("fileopen","mode"); 

Por exemplo,

 fopen("E:\cprogram\newprogram.txt","w"); fopen("E:\cprogram\oldprogram.bin","rb");
  • Suponhamos que o arquivo newprogram.txtnão exista no local E:cprogram. A primeira função cria um novo arquivo chamado newprogram.txte o abre para gravação de acordo com o modo 'w' .
    O modo de gravação permite criar e editar (sobrescrever) o conteúdo do arquivo.
  • Agora, vamos supor que o segundo arquivo binário oldprogram.binexista no local E:cprogram. A segunda função abre o arquivo existente para leitura no modo binário 'rb' .
    O modo de leitura permite apenas a leitura do arquivo, você não pode gravar no arquivo.
Modos de abertura em E / S padrão
Modo Significado do Modo Durante a inexistência de arquivo
r Aberto para leitura. Se o arquivo não existir, fopen()retorna NULL.
rb Abra para leitura em modo binário. Se o arquivo não existir, fopen()retorna NULL.
w Abra para escrita. Se o arquivo existir, seu conteúdo será sobrescrito.
Se o arquivo não existir, ele será criado.
wb Abra para escrita em modo binário. Se o arquivo existir, seu conteúdo será sobrescrito.
Se o arquivo não existir, ele será criado.
a Abra para anexar.
Os dados são adicionados ao final do arquivo.
Se o arquivo não existir, ele será criado.
ab Abra para anexar no modo binário.
Os dados são adicionados ao final do arquivo.
Se o arquivo não existir, ele será criado.
r+ Aberto para leitura e escrita. Se o arquivo não existir, fopen()retorna NULL.
rb+ Abra para leitura e gravação em modo binário. Se o arquivo não existir, fopen()retorna NULL.
w+ Aberto para leitura e escrita. Se o arquivo existir, seu conteúdo será sobrescrito.
Se o arquivo não existir, ele será criado.
wb+ Abra para leitura e gravação em modo binário. Se o arquivo existir, seu conteúdo será sobrescrito.
Se o arquivo não existir, ele será criado.
a+ Abra para leitura e acréscimo. Se o arquivo não existir, ele será criado.
ab+ Abra para ler e anexar no modo binário. Se o arquivo não existir, ele será criado.

Fechando um Arquivo

O arquivo (texto e binário) deve ser fechado após a leitura / gravação.

O fechamento de um arquivo é executado usando a fclose()função.

 fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that fprint() and fscanf() expects a pointer to the structure FILE.

Example 1: Write to a text file

 #include #include int main() ( int num; FILE *fptr; // use appropriate location if you are using MacOS or Linux fptr = fopen("C:\program.txt","w"); if(fptr == NULL) ( printf("Error!"); exit(1); ) printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; ) 

This program takes a number from the user and stores in the file program.txt.

After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file

 #include #include int main() ( int num; FILE *fptr; if ((fptr = fopen("C:\program.txt","r")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; ) 

This program reads the integer present in the program.txt file and prints it onto the screen.

If you successfully created the file from Example 1, running this program will get you the integer you entered.

Other functions like fgetchar(), fputc() etc. can be used in a similar way.

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

Writing to a binary file

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

  1. address of data to be written in the disk
  2. size of data to be written in the disk
  3. number of such type of data
  4. pointer to the file where you want to write.
 fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","wb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); ) fclose(fptr); return 0; ) 

In this program, we create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.

Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the data.

Finally, we close the file.

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.

 fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); ) fclose(fptr); return 0; ) 

In this program, you read the same file program.bin and loop through the records one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num.

You'll get the same records you inserted in Example 3.

Getting data using fseek()

If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek().

As the name suggests, fseek() seeks the cursor to the given record in the file.

Syntax of fseek()

 fseek(FILE * stream, long int offset, int whence);

The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.

Diferente de onde em fseek ()
De onde Significado
SEEK_SET Inicia o deslocamento do início do arquivo.
SEEK_END Inicia o deslocamento do final do arquivo.
SEEK_CUR Inicia o deslocamento a partir da localização atual do cursor no arquivo.

Exemplo 5: fseek ()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) // Moves the cursor to the end of the file fseek(fptr, -sizeof(struct threeNum), SEEK_END); for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR); ) fclose(fptr); return 0; ) 

Este programa começará a ler os registros do arquivo program.binna ordem inversa (do último ao primeiro) e os imprimirá.

Artigos interessantes...