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

0
#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 an array of char, but I need to know the total of characters. The value of the counter gets either 0 or a strange value, moreover, the array is only storing garbage values from memory.

    
asked by anonymous 02.08.2017 / 16:41

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 size of the file exceeds the size of available memory.

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 file in C ++:

#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;
}
    
02.08.2017 / 17:14