Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

write a c programme for file handling functions

+3 votes
asked Feb 15, 2023 by SRI DATTA (160 points)

1 Answer

+1 vote
answered Feb 16, 2023 by Douglas Pinto do Nascimento (270 points)

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;
}

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...