How to count elements of a C File?

Asked

Viewed 1,020 times

0

I have the following problem to solve the college, but so far I have not seen a valid solution... I made the following code up to the time of sending since help request.

inserir a descrição da imagem aqui

//
//  2.c
//  IFTM Exercises
//
//  Created by Lelre Ferreira on 10/17/19.
//  Copyright © 2019 Lelre Ferreira. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main (int argc, const char * argv[]){


    FILE *p;
    char texto[20];
    char pular = '\n';
    int i = 0, count = 0, rpt = 1;

    p = fopen("Text.txt", "w");
    if (p == NULL) {
        printf("Erro na leitura");
        exit(1);
    }

    while(rpt != 0){
        printf("Digite uma linha: ");
        scanf("%s",      texto);
        fprintf(p, "%s", texto);

        printf("Deseja repetir? ");
        scanf("%d", &rpt);
    }
    fclose(p);

    p = fopen("Text.txt",  "w");
    fread(&texto, sizeof(char), 20, p);
    for (i = 0; i < strlen(texto); i++) {
        if (fscanf(p, "%s\n", &texto[i]) == pular) {
            count++;
        }
    }
    fclose(p);

    printf("Total de linhas: %d\n", count);
    return 0;

}

Could someone give me a hint on how to solve the above problem?

  • It makes no sense to use fread and fscanf mixed in the same file. Certainly fread is not the best option for reading a text file. Another consideration: if the end of the file is detected and the character read immediately before is not a ' n' you should not add 1 to the number of lines?

1 answer

1

Leire,

Below is a commented example of how to do this reading, and the file name will be asked to the user:

#include<stdio.h>

int main(int argc, char *argv[]) {
  //Nome do arquivo
  char nomeDoArquivo[50];

  printf("Qual o nome do arquivo: ");

  //Solicita o usuário o nome do arquivo que será avaliado a quantidade de linhas
  scanf("%s", nomeDoArquivo);

  //Abre o arquivo como leitura
  FILE *fp = fopen(nomeDoArquivo,"r");

  if (fp == NULL) {
    //Sai do programa caso o arquivo não tenha sido aberto
    printf("Erro ano tentar abrir o arquivo.");
    return 1;
  } else {
    int ch = 0;
    int linhas = 0;

    linhas++;

    //Efetua a contagem de linhas lendo o arquivo e procurando a quebra de linha
    while (!feof(fp)) {
      ch = fgetc(fp);

      if (ch == '\n') {
        linhas++;
      }
    }

    //Fecha o arquivo
    fclose(fp);

    //Exibe a quantidade de linhas
    printf("Quantidade de linhas: %d\n",linhas);

    return 0;
  }
}

Here you can execute this code: https://repl.it/repls/VividEarnestShelfware


This is just an example, there are always different ways to get the same result, see here another example: Count lines of a txt file in c / c++

  • Daniel! Thanks, I’m starting to see files now. Actually it’s already been past the explanations but I ended up missing and I’m trying to recover. I had no knowledge yet about feof, fgetc among others. I have some more activities similar to this I will put in practice! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.