How to count the total Characters of a txt file, including spaces and ' n'?

Asked

Viewed 2,467 times

1

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

int main(int argc, char *argv[]) {
    FILE *arquivoRead; 
    FILE *arquivoEscrita; 
    char ch; 
    int count=0;
    int lin, col;


    arquivoRead = fopen(argv[3], "r"); 

    if(arquivoRead == NULL) {
        fprintf(stderr, "Erro na abertura do arquivo\n");
    }

    if(argc < 1) {
        fprintf(stderr, "Quantidade insuficiente de parâmetros\n");
    }

    if(strcmp(argv[1], "-d") == 0 ) {

    }


    arquivoEscrita = fopen("arquivoEscrita.txt", "w");

    while( (ch=fgetc(arquivoRead) ) != EOF ){

        fprintf(arquivoEscrita, "%c", ch);
        fprintf(stdout, "%c", ch);

      count++;

    }

    char matriz[count][count];

    while( (ch=fgetc(arquivoRead) ) != EOF ){
        for(lin=0; lin<count; lin++){
            for(col=0; col<count; col++){
                matriz[lin][col] = ch;
            }
        }
    }

    printf("\n\n");

    for(lin=0; lin<count; lin++){
        for(col=0; col<count; col++){
            fprintf(stdout, "%c ", matriz[lin][col]);
        }
        printf("\n");
    }



    fclose(arquivoRead);

    fclose(arquivoEscrita);

    return 0;
}

I’m trying to put all these characters in a char matrix, but I need to know the total of characters. The value of the counter either gets 0 or a strange value, besides, the matrix is only storing junk values of memory.

  • Take a look at this site: http://www.cplusplus.com/reference/cstdio/feof/

1 answer

1

You do not need to load the contents of a file into memory to calculate its total size, this becomes impractical in cases where the file size exceeds the available memory size.

Calculating the size (in bytes) of a file in the C language:

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

int main( int argc, char * argv[] )
{
    FILE * fp = fopen( argv[1], "r" );
    fseek( fp, 0L, SEEK_END );
    long tam = ftell(fp);
    fclose(fp);
    printf("Tamanho total do arquivo: %ld bytes\n", tam );
    return 0;
}

Calculating the size (in bytes) of a C file++:

#include <iostream>
#include <fstream>

int main( int argc, char * argv[] )
{
    std::ifstream in( argv[1], std::ifstream::ate | std::ifstream::binary );
    long tam = in.tellg();
    std::cout << "Tamanho total do arquivo: " << tam << " bytes" << std::endl;
    return 0;
}

Browser other questions tagged

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