Doubt with excel files

Asked

Viewed 48 times

0

I have a list of dates in a BTH.cvs excel file. I want to copy the entire file to another new.cvs, but a.exe stops working.

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

int main(int argc,char **argv){
    FILE *in = fopen("BTH.csv", "r");
    FILE *out = fopen("novo.csv", "w");



        while(!feof(in)){
            int num;
            fscanf(in, "%d", &num);

            fprintf(out, "%d", num);

        }




    fclose(in);
    fclose(out);


    return 0;
}

1 answer

1

The problem is that the csv file has more than just numbers that it won’t be able to read with %d. Although you can try to change your algorithm for this case, for example with sscanf I think it’s easier to go the other way.

Using the same idea of this my other answer can do so:

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

int main()
{
    FILE *in = fopen("BTH.csv", "r");
    fseek (in, 0, SEEK_END); //posicionar-se no fim
    long dimensao = ftell (in); //descobrir a dimensão
    fseek (in, 0, SEEK_SET); //voltar ao inicio

    //alocar espaço para ler tudo
    char *dados = (char*) malloc(dimensao * sizeof(char)); 

    if(dados){ //se conseguiu alocar
        fread (dados, 1, dimensao, in); //ler tudo
        FILE *out = fopen("novo.csv", "w"); //abrir o destino para escrita
        fwrite(dados, dimensao, 1 , out); //escrever todo o conteudo
        fclose(out);
    }

    fclose(in);
    return 0;
}

There are several other alternatives as well as for example, running a file copy by the operating system with the appropriate command.

It would also be relevant to write the respective error messages either for when you were unable to allocate the necessary reading space, or for when opening any of the FILE* was unsuccessful.

Browser other questions tagged

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