How do I create a CSV in C by incrementing the first number?

Asked

Viewed 72 times

1

I ran that csv:

1;0
2;0
2;0
2;0
2;1
2;2
2;2
2;2
2;2
2;3

...

How to get from this file the first number of each line to increment it?

And there’s like the first line not to be skipped?

int gerarRelatorioHash(int colisoes) {
     FILE *pont_arq;

     pont_arq = fopen("relatorio.csv", "r+");

     if(pont_arq == NULL) {
        printf("Erro na abertura do arquivo!");
        return 1;
    }

    int qtd;
    fscanf(pont_arq, "%d", &qtd);
    qtd++;

    fseek(pont_arq, 0, SEEK_END);\
    fprintf(pont_arq, "\n%d;%d", qtd,colisoes);

    fclose(pont_arq);
    printf("Dados gravados com sucesso!\n");
    return 0;
}

The idea that the qtd be an accountant to whom every line he jumps he makes a qtd++ and the second parameter is what was passed.

An example of how it should have turned out:

1;0
2;0
3;0
4;0
5;1
6;2
7;2
8;2
9;2
10;3
....
  • 1

    You could edit your question and put the example of your file with more lines to be clearer?

1 answer

3


Instead of changing the input file, you can simply convert it by writing an output file with the new content, see only:

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

#define LINHA_MAX_LEN  (256)

int main( int argc, char ** argv )
{
    int n = 0;
    int seq, val;
    char linha[ LINHA_MAX_LEN + 1 ];
    FILE * in = NULL;
    FILE * out = NULL;

    in = fopen( argv[1], "r");

    if(!in)
    {
        printf("Erro abrindo arquivo de entrada para leitura.\n");
        return 1;
    }

    out = fopen( argv[2], "w");

    if(!out)
    {
        printf("Erro abrindo arquivo de saida para gravacao.\n");
        fclose(in);
        return 1;
    }

    /* Para cada linha do arquivo de entrada */
    while( fgets( linha, sizeof(linha), in ) )
    {
        /* Incrementa contador de linhas */
        n++;

        /* Interpreta linha lida */
        sscanf( linha, "%d;%d\n", &seq, &val );

        /* Grava a linha com novo sequencial no arquivo de saida */
        fprintf( out, "%d;%d\n", n, val );
    }

    fclose(in);
    fclose(out);

    printf("Linhas Processadas: %d\n", n );

    return 0;
}

Testing:

$ ./enumerar relatorio.csv saida.csv
Linhas Processadas: 10

Entree (relatorio.csv):

1;0
2;0
2;0
2;0
2;1
2;2
2;2
2;2
2;2
2;3

Exit (saida.csv):

1;0
2;0
3;0
4;0
5;1
6;2
7;2
8;2
9;2
10;3

Browser other questions tagged

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