This code illustrates the following file manipulation functions:
- 'fopen': opens a file with a certain mode (reading, writing, etc.).
- 'fprintf': writes to the file in the same format as printf.
- 'fputs': writes a string to the file.
- 'fclose': closes the open file.
- 'fgets': reads a line from the file into a string.
Note that the code also verifies that the file opened correctly, using a test to see if the file pointer is null. This is important for dealing with file handling errors.
#include <stdio.h>
int main() {
FILE *fp; // ponteiro para o arquivo
char nome_arquivo[] = "exemplo.txt";
char linha[100];
// abrir arquivo para escrita
fp = fopen(nome_arquivo, "w");
// verificar se o arquivo foi aberto corretamente
if (fp == NULL) {
printf("Erro ao abrir o arquivo.\n");
return 1;
}
// escrever no arquivo
fprintf(fp, "Hello, world!\n");
fputs("Esta é uma linha de exemplo.", fp);
// fechar arquivo
fclose(fp);
// abrir arquivo para leitura
fp = fopen(nome_arquivo, "r");
// verificar se o arquivo foi aberto corretamente
if (fp == NULL) {
printf("Erro ao abrir o arquivo.\n");
return 1;
}
// ler o arquivo linha por linha
while (fgets(linha, 100, fp) != NULL) {
printf("%s", linha);
}
// fechar arquivo
fclose(fp);
return 0;
}